Example object inside:
function MyComponent() {
return (
<div style={{color: 'green', fontSize: '20px', backgroundColor: 'yellow',}}>
Styled content
</div>
);
}
Example object outside:
const styles = {
color: 'blue',
fontSize: 16, // px assumed
fontWeight: 'bold',
};
function MyComponent() {
return <div style={styles}>Styled content</div>;
}
Another object outside:
function MyComponent() {
const styles = {
color: 'green',
fontSize: '2rem', // using different length unit
backgroundColor: 'yellow',
};
return <div style={styles}>Styled content</div>;
}
Using the style attribute and JavaScript objects. Write style properties in camelCase. Px is assumed but can be changed to any other length unit using quotes.
Inside Style Sheet:
/* styles.css */
.myClass {
color: blue;
font-size: 16px;
font-weight: bold;
}
Inside JS file:
import React from 'react';
import './styles.css';
function MyComponent() {
return <div className="myClass">Styled content</div>;
}
To use CSS stylesheets in React, using classes.
import React, { useState } from 'react';
import './styles.css';
function ExampleComponent() {
const [isDisplayed, setIsDisplayed] = useState(true);
const handleButtonClick = () => {
setIsDisplayed(!isDisplayed);
}
return (
<div>
<button onClick={handleButtonClick}>Toggle Display</button>
<div style={{ display: isDisplayed ? 'block' : 'none' }}>
{/* Content */}
</div>
</div>
);
}
export default ExampleComponent;
Styles can also be changed using JavaScript. Using numbers, strings, objects, arrays, and booleans are all good to use for dynamic styling.