How to change the style of a React component when you click a button?

1

I am using React and I am creating some components, I am very new to react, I am styling the components in an external css file and importing, however I need to do a side bar that I need to open and close when I click on a button, that this is going to suck, is there an ideal way in the react to stylize and change the style when there is a click of a button?

    
asked by anonymous 27.03.2018 / 23:14

2 answers

2

Here I comment on three ways to define style.

(1) Traditional way

  

Create an individual file for the style sheet that will be used throughout the app.

Problem: It may be that not all styles are used by the app or in case you make a reusable component, another consumer of your component will depend on the specific styles for your app

(2) CSS inline with style

  

Define the style of each inline component using prop style

Problem: Leaves style coupled with structure and implementation of elements. It may be less efficient than externally defined CSS. It should only be used in case external CSS does not solve the problem in mind.

(3) Separate CSS files for each component (my recommendation)

  

Define a CSS file for each component

I recommend this way because:

(a) separates style from implementation and implementation

(b) usually more efficient than inline

(c) files are separate but can be combined into one using a bundler like Webpack

(d) allows you to redistribute a reusable component without having to include a style sheet with rules that has nothing to do with the component in question.

Example

Button.js

import 'Button.css';

const Button = (props) => (
  <button type="button" className="btn">{props.children}</button>
);

Button.css

.btn {
  padding: 20px 30px;
}

/* mais outros estilos relacionado somente à esse componente */

The style is imported into the component itself. Bundlers like the Webpack allow you to do this. There is a plugin that extracts CSS from within the JS file as well.

    
28.03.2018 / 23:45
1

Man, there is no secret, you will have a state to control the action of the click, with the click executing the state change the component will be re-invented, that is, it will go through the rendering method again ... just make a conditional in the className of the element you want to change with CSS.

    
18.04.2018 / 21:49