Hello friends,
Welcome to the new post about using CSS in React. This post will look into adding dynamic inline style and dynamically setting CSS classes. We will also look into styled components in react and how to use props with styled-components too. Lastly, we will look into how to use the CSS Module and apply a dynamic style with it. so a lot to learn, let us go ahead and answer the various questions on CSS in react one by one.
Table of Contents
- What is CSS and why we want to apply css in react?
- How to add dynamic inline style in react?
- How to set CSS class dynamically?
- What is a styled component in React?
- How to use react styled component?
- Can I use props with styled component?
- What is CSS Module in React?
- How to use CSS Module for styling React component?
- Conclusion
- Other important topics on React which you might be interested
What is CSS and why we want to apply css in react?
CSS stands for Cascading Style Sheets and we can use CSS to make web application UI attractive and usable to end users. We can write react app using the function or class component but if we will not apply any style to it, that will look like a skeleton and more like a POC (proof of concept) app also style makes the app attractive and usable to end users. so, CSS and styling a react application or more largely any end-user-facing application is very important.
How to add dynamic inline style in react?
Let’s look at how we can apply a dynamic inline style to react component. I have added Newsletter. tsx and Newsletter.css file in a component folder in the same app which we are using as a sample app in previous blog posts too as below.
Let’s update the Newsletter component and App component code just to test it works.
below is the updated code for Newsletter.tsx
const Newsletter = (props: any) => {
return <p>Newsletter works</p>;
};
export default Newsletter;
Below is updated App.tsx.
import Newsletter from "./components/Newsletter";
function App() {
return (
<div>
<h2>my App</h2>
<Newsletter></Newsletter>
</div>
);
}
export default App;
Once you run the app using npm init. here is the output below
Now update Newsletter.tsx to add one input and button as below
const Newsletter = (props: any) => {
return (
<div>
<input type="text" id="fullName" name="fullName" />
<br />
<input type="submit" value="Submit" />
</div>
);
};
export default Newsletter;
Let see how it looks without any css
How we want that when users type something in the text box the button should look different and when it is blank, it should look different. Here is the updated code for Newsletter. tsx
import { useState } from "react";
const Newsletter = (props: any) => {
const [fullName, setFullName] = useState("");
const fullNameChangeHandler = (event: any) => {
setFullName(event.target.value);
};
return (
<div>
<input
type="text"
id="fullName"
name="fullName"
onChange={fullNameChangeHandler}
/>
<br />
<input
style={{
background: fullName.length > 0 ? "blue" : "grey",
color: fullName.length > 0 ? "white" : "black",
}}
type="submit"
value="Submit"
/>
</div>
);
};
export default Newsletter;
In the above-highlighted code, we are setting the dynamic inline style for submit button. If the “fullName” is blank then we are setting the background to grey and color to black as below
and when user type something in text box the button background changes to blue and color changes to white as below
the style property takes an object as input and we are passing the javascript equivalent for the CSS properties for applying that for example background and color.
This is how we can set dynamic inline style in react.
How to set CSS class dynamically?
Now, In the above approach we are adding every style element one by one like background and color, If we want to apply multiple style elements to an HTML element we generally prefer to use CSS class for the same. Let us update the Newsletter.css file with two classes that we want to apply to the button element as below.
.submit_valid{
background-color: blue;
color:white
}
.submit_invalid{
background-color:gray;
color: black;
}
Now let us update the Newsletter.tsx file as below to apply the above classes dynamically.
import { useState } from "react";
import "./Newsletter.css";
const Newsletter = (props: any) => {
const [fullName, setFullName] = useState("");
const fullNameChangeHandler = (event: any) => {
setFullName(event.target.value);
};
return (
<div>
<input
type="text"
id="fullName"
name="fullName"
onChange={fullNameChangeHandler}
/>
<br />
<input
className={fullName.length > 0 ? "submit_valid" : "submit_invalid"}
type="submit"
value="Submit"
/>
</div>
);
};
export default Newsletter;
In the first highlighted line above we are importing the CSS file and in the later highlighted line we are applying the CSS class dynamically.
If the fullName is blank then we are setting the background to grey and color to black as below
and when the user types something in the text box the button background changes to blue and the color changes to white as below
This is how we can apply css class dynamically in react.
What is a styled component in React?
If you are working with a large react app where you have many team members working on different components/features then it could possible that your CSS class and other team members’ class may have a conflict. he/she may also define a CSS class with the same name, applying on same elements, in that case, it would be hard to debug and find out and you will have to fix both components/ components which are affected by this problem. The react styled component solves exactly this problem where the CSS file is not separate and it combines CSS with the component itself.
How to use react styled component?
To use styled component in react you need to run the following command using npm
npm install --save styled-components
you may get the similar output on terminal once you run the above command
Now, the styled component installation is done, We need to install one more package as we are using the react with typescript. If we will not install the below package we will get the error “Could not find a declaration file for ‘styled-components’ “. you can read more about this error here
npm i --save-dev @types/styled-components
let us update our Newsletter component to use the styled components as below.
import styled from "styled-components";
import { useState } from "react";
function Newsletter() {
const [fullName, setFullName] = useState("");
const fullNameChangeHandler = (event: any) => {
setFullName(event.target.value);
};
const SubmitButton = styled.button`
background-color: ${fullName.length > 0 ? "blue" : "grey"};
color: ${fullName.length > 0 ? "white" : "black"};
`;
return (
<div>
<input
type="text"
id="fullName"
name="fullName"
onChange={fullNameChangeHandler}
/>
<br />
<SubmitButton>Submit</SubmitButton>
</div>
);
}
export default Newsletter;
Let us look at the above-highlighted code, first, we are importing the styled component and then we are adding a button using style. button method to build a button, also checks how we are using “fullName” which is a state variable inside the styled component. The benefit of using a styled component in react is we don’t need to maintain an extra CSS file and the component code and CSS are together. Let us see if we are getting the same functionality with the styled component or not.
This is the look when the textbox is blank.
This is when we start typing on textbox.
When we work with large projects, we may develop some component and their CSS too but as the project gets bigger and we realize that we don’t need that component. We tried to remove that component but sometimes missed removing the unnecessary CSS and we are not clear that how to find all the places where this CSS is impacting. The styled component helps us to solve this problem too, as the component itself contains the CSS and when we remove the not used component later in the project cycle, the CSS is also removed with that.
The styled component makes unique classes and that is applied to the element only and this also helps us to remove unwanted css from project as it large projects. here is the unique classes generated by styled component in my project.
You can read more about react styled component by going to official site.
Can I use props with styled component?
Yes, you can use props in the styled component. Let us update our example code to use props. I have added the new component name “NewsLetterSubmitButton” in the components folder in the application. here is the code for the “NewsLetterSubmitButton” component.
import styled from "styled-components";
const NewsLetterSubmitButton = (props: any) => {
const SubmitButton = styled.button`
background-color: ${props.fullName.length > 0 ? "blue" : "grey"};
color: ${props.fullName.length > 0 ? "white" : "black"};
`;
return <SubmitButton>Submit</SubmitButton>;
};
export default NewsLetterSubmitButton;
In above , the “NewsLetterSubmitButton” is regular function component of react and if we are using styled button in that. If you notice the highlighted code , we are using props.fullName instead of fullName as we are passing fullName as props for “NewsLetterSubmitButton” component from “Newsletter” component. Here is the updated code of “Newsletter” component.
import { useState } from "react";
import NewsLetterSubmitButton from "./NewsLetterSubmitButton";
function Newsletter() {
const [fullName, setFullName] = useState("");
const fullNameChangeHandler = (event: any) => {
setFullName(event.target.value);
};
return (
<div>
<input
type="text"
id="fullName"
name="fullName"
onChange={fullNameChangeHandler}
/>
<br />
<NewsLetterSubmitButton fullName={fullName}></NewsLetterSubmitButton>
</div>
);
}
export default Newsletter;
In above “Newsletter” component we have moved the styled component related code to “NewsLetterSubmitButton” component and then importing and using that in “Newsletter” component. This is how we can use props in react styled component. If you run the application, it should work as before.
What is CSS Module in React?
The styled component works great however, you might want to use a separate CSS file for applying CSS in react component also, you do not want to face problems like unused CSS, CSS conflicts, and others which we may get in the large project if using just a CSS file for a component. The CSS module just serves this purpose by generating unique classes for applied elements in react component. The CSS modules are available with create react app and you can read more about it by going to the official site here.
How to use CSS Module for styling React component?
To use the css module you need to create component css file named as “[name].module.css” and then import that using any name which you want. Let us update our previous example component by using css module.
In the above , we have renamed the Newsletter.css to Newsletter.module.css. There is no change in the newsletter.module.css file content which is as below.
.submit_valid{
background-color: blue;
color:white
}
.submit_invalid{
background-color:gray;
color: black;
}
Now let us look the updated Newsletter.tsx code.
import { useState } from "react";
import styles from "./Newsletter.module.css";
const Newsletter = (props: any) => {
const [fullName, setFullName] = useState("");
const fullNameChangeHandler = (event: any) => {
setFullName(event.target.value);
};
return (
<div>
<input
type="text"
id="fullName"
name="fullName"
onChange={fullNameChangeHandler}
/>
<br />
<input
className={
fullName.length > 0 ? styles.submit_valid : styles["submit_invalid"]
}
type="submit"
value="Submit"
/>
</div>
);
};
export default Newsletter;
In the above code, we are importing the module file as you can see in the first highlighted line. next, we are using it to access different properties using the name “styles” which is the name we have given at the time of import. also, I tried to use different ways of accessing CSS properties defined in the “newsletter.module.css” file in the above code.
This does not make any diffirence in the output and it should be working as before.
The difference is how the CSS module applies CSS to the element. let us look at that in developer tools in the browser.
As you can see it not applied the same classes to the element but named it to scope the component which makes the classes unique and help minimize the problem related to applying plan CSS.
This is how we can use css module in react.
Conclusion
In the above post, we looked into applying CSS in react in full detail. We started with the basics of what is CSS and then we answered why we want to apply CSS in react. after that, we looked into setting dynamic inline style and CSS classes in react component, further, we learned about styled components and also worked on examples of using styled-components and then refactored the example to use props with the styled component. lastly, we learned about CSS modules and how they can be used in react components.
as you have learned, there are multiple ways of using CSS in react but the choice is yours and on the project’s needs only. You should evaluate every approach to your project needs and choose the best fit only.
Other important topics on React which you might be interested
React Fragments | A modern way to return multiple elements (codelila.com)
Thanks and Happy Learning :). Please give your valuable feedback and share this post if you liked and learned something from this post.