How to change the style of an React component by clicking a button?

Asked

Viewed 3,949 times

1

Guys I’m using React and I’m creating some components, I’m very beginner in React, I’m styling the components in an external css file and importing, but I need to make a side bar q need to open and close when clicked on a button, I realized that this will give a lot of shit, there is an ideal way in React to style and change the style when there is a click of a button?

2 answers

2

Here I comment on three ways to define the 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

Set the style of each inline component using the prop style

Problem: Leaves style coupled with the structure and implementation of the elements. It may be less efficient than externally defined CSS. 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:

(to) separates the style of the estuary and implementation

(b) usually more efficient than inline

(c) files are separated 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 have 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 allows you to do this. There is a plugin that extracts CSS from within the JS file also.

1

Dude, there is no secret, you will have a state to control the click action, with the click running the change of state the component will be reengineered, IE, vai passar de novo pelo metódo render... So just make a conditional on the classname of the element you want to change with CSS.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.