Welcome back to CodeYourCraft! Today, we're diving into a fascinating aspect of React JS - Dynamic Styling. This lesson is perfect for beginners and intermediates who are eager to learn more about styling components in a dynamic and efficient manner. Let's get started! 🚀
Dynamic Styling in React allows you to change the style of components based on certain conditions, user interactions, or even data fetched from APIs. This makes your application more responsive and adaptable to different situations.
React provides multiple ways to style components, but we'll focus on two main approaches: Inline Styles and CSS Modules.
Inline Styles are ideal for small, one-off styling needs. They are applied directly to the component as an object within the JSX syntax.
function Welcome(props) {
const style = {
fontSize: '1.5em',
color: props.color
};
return <h1 style={style}>Hello, {props.name}!</h1>;
}CSS Modules allow you to write encapsulated CSS that is scoped to individual components. This helps prevent naming collisions and makes your code more organized.
To use CSS Modules, create a .css file for your component and import it with the css function from the styled-components package.
import styles from './Welcome.module.css';
function Welcome(props) {
return <h1 className={styles.welcome}>Hello, {props.name}!</h1>;
}
// In Welcome.module.css
.welcome {
font-size: 1.5em;
color: props.color;
}To make styling dynamic, we can use JavaScript expressions to compute the style object.
function Toggle(props) {
const [isToggleOn, setIsToggleOn] = React.useState(true);
const style = {
backgroundColor: isToggleOn ? 'green' : 'red'
};
return (
<button style={style} onClick={() => setIsToggleOn(!isToggleOn)}>
{isToggleOn ? 'On' : 'Off'}
</button>
);
}With CSS Modules, you can use JavaScript variables to make your styles dynamic.
import styles from './Toggle.module.css';
function Toggle(props) {
const [isToggleOn, setIsToggleOn] = React.useState(true);
return (
<div className={styles.toggle}>
<div
className={`${styles.slider} ${isToggleOn ? styles.on : styles.off}`}
onClick={() => setIsToggleOn(!isToggleOn)}
></div>
</div>
);
}
// In Toggle.module.css
.toggle {
display: inline-flex;
box-sizing: border-box;
width: 60px;
height: 34px;
position: relative;
cursor: pointer;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #595959;
-webkit-transition: .4s;
transition: .4s;
}
.slider.on {
left: 34px;
}
.slider.off {
left: 0;
}Now that you've learned about Dynamic Styling in React, let's put your skills to the test!
What is Inline Styling used for in React?
Keep learning and coding with CodeYourCraft! 🚀💻