user7776690
user7776690

Reputation:

React Add Css to Component without addon library

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?

Upvotes: 1

Views: 514

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104389

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.

Upvotes: 2

Related Questions