Reactjs Styling Components / React with CSS
There are three different ways of reactjs styling components with CSS:-
- React Inline Style
- External Stylesheet
- CSS Module
React Inline Styling
In React, JSX provide us an attribute 'style'. This attribute accepts javascript object with property in camelCase (backgroundColor instead of background-color). You know that in JSX, javascript code is written within curly braces. Javascript object also use curly braces so to do styling, we have to write two curly braces, one is to write javascript code in JSX and other is to write javascript object.
We will write JSX element <button> and attribute style with property. Below is example of inline style in react:-
import React from 'react';
const App = () => {
return(
<button style={
{backgroundColor:'lightblue',
border:'1px solid black',
borderRadius:'20px',
fontSize: 24,
width:'200px',
height:'50px'}
}>Button</button>
);
}
export default App;
Or we can write separate object and use within JSX as
import React from 'react';
const btnStyle = {
backgroundColor:'lightblue',
border:'1px solid black',
borderRadius:'20px',
fontSize: 24,
width:'200px',
height:'50px'
};
const App = () => {
return(
Button
</button>
);
}
export default App;
We can write both in JSX using spread operator (…) as
import React from 'react';
const btnStyle = {
backgroundColor:'lightblue',
border:'1px solid black',
borderRadius:'20px',
fontSize: 24
};
const App = () => {
<button
style={{...btnStyle, ...{width:'200px', height:'50px'}}}>
</button>
);
}
export default App;
In all above cases, output will be same as below
External Stylesheet
Create a separate CSS file and write CSS classes in it. You can create multiples CSS files. In production, all CSS files will be merged into a single minified CSS file. Import this CSS file in react component. Use className instead of class as className='btnStyle'
App.css
.btnStyle{
background-color:lightblue;
border:1px solid black;
border-radius:20px;
font-size: 24px;
width:200px;
height:50px;
}
Import and use App.css in App.jsx
import React from 'react';
import './App.css';
const App = () => {
return(
<button className='btnStyle'>
Button
</button>
);
}
export default App;
Output in browser
React CSS Module
Create a separate CSS file with module.css as App.module.css. Import it in file where you want to use. Now you can use styles like javascript objects as
App.module.css
.btnStyle{
background-color:lightblue;
border:1px solid black;
border-radius:20px;
font-size: 24px;
width:200px;
height:50px;
}
Import and use App.module.css in App.jsx
import React from 'react';
import Style from './App.module.css';
const App = () => {
return(
<button className={Style.btnStyle}>
Button
</button>
);
}
export default App;
Output in browser
Post a Comment