1

I have created a react component. In this case its a component called Header.js.

Here is the code:

import React from "react";

export class Header extends React.Component {

    render() {

        return (

            <div>   
                <h1>Header Component</h1>
            </div>

        );

    }

}

What I need to do now is to add some css to the same component file so inside the js.

I need to do this without using addon libraries like jss etc.

How can I do this?

1 Answer 1

2

You can apply css by following ways:

1. Directly with HTML element:

import React from "react";
export class Header extends React.Component {
    render() {
        return (
            <div style={{fontSize: '10px'}}>   
                <h1>Header Component</h1>
            </div>
        );
    }
}

2. You can define the css object in the starting of the file then use those object in style attribute:

let style = {
   a: {fontSize: '10px'}
};

import React from "react";
export class Header extends React.Component {
    render() {
        return ( <div style={style.a}>   
                <h1>Header Component</h1>
            </div>
        );
    }
}

Note: 2nd way is a better way, because it will help you to maintain the code, it makes code clean, compact, more readable and easily maintainable.

Sign up to request clarification or add additional context in comments.

4 Comments

Is it possible to include :hover etc without adding any addons/libraries? If not, I hope react includes it in the future :)
in these above ways, directly hover will not work. For that you need to use classes. Assign class to any html element, then define that class in index.html file or in external css file, there you can define onhover, and it will work :)
Do you know if the React developers are thinking on extending this functionality in react core?
@dj2017 sorry, no idea about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.