karfkars
karfkars

Reputation: 4063

how to manage style in ReactJs

I am trying to learn react. I see a lot of style change inside java script so far. As far as I know, the style should onle be managed by css files. But I am not sure this rule also applies to React. What is the best practice for react. For instance, is the following code a clean code, or is changing the style in the React component a smell and need to be refactored? If so, how it could be refactored?

“const Color = ({ title, color}) =>
    <section className="color">
        <h1>{title}</h1>
        <div className="color" 
             style={{ backgroundColor: color }}>
        </div>
    </section>”

Upvotes: 1

Views: 240

Answers (3)

Dm Mh
Dm Mh

Reputation: 840

I prefer to connect external .css file - it's much more clean. If there is a need to keep styles in .js I would organize the code in that way:

const styles = {
color: 'red',
fontSize: '2rem',
backgroundColor: 'forestgreen'
}

And I would apply the styles I need just like here:

<div style={{color: styles.color, fontSize: styles.fontSize}}></div>

Or, If I need to apply all styles:

<div style={styles}></div>

Upvotes: 2

Lazar Nikolic
Lazar Nikolic

Reputation: 4394

You can also use styled components https://www.styled-components.com/

Upvotes: 1

Sakhi Mansoor
Sakhi Mansoor

Reputation: 8102

That is totally depends on our requirement and preferences. Inline styles are concerned with only component they are written into. You can structure css based on your components so it becomes reusable. You can declare your css in to your components in variables as well as in separate asssets directory.

Well it is more about code readability and re-usability. Webpack writes your all css/scss in a single file and inject into your index.html. You should look into JSS so you can compile your css and later inject it into your component as props. Anyways there are a lot of resources that you can leverage from.

Upvotes: 2

Related Questions