This content originally appeared on DEV Community and was authored by Saleh-Mubashar
Hi guys!.
In this post, we will be looking into the 3 best ways CSS code can be added in React JS or to you React App.
Obviously, CSS is crucial in making your app user friendly and visually attractive. These are the 3 different ways to add CSS to your react app:
1 - External Stylesheet
You can create a new CSS file in your project directory and add your CSS inside it. You can then import it in your component, class or React JS page.
The following code is used to import an external CSS stylesheet.
import "./styles.css";
2 - Inline CSS
Probably the most common and quickest out of all 3 is inline CSS. However it has many disadvantages and it is generally discouraged to use unless it is a very small application.
Basically, we create an object that contains different references which are then called using the style{}
attribute.
For example, the CSS is added like this:
const styles = {
section: {
fontSize: "18px",
color: "#292b2c",
backgroundColor: "#fff",
padding: "0 20px"
},
wrapper: {
textAlign: "center",
margin: "0 auto",
marginTop: "50px"
}
}
It is then added to an element like this:
<section style={styles.section}>
<div style={styles.wrapper}>
</div>
</section>
3 - Styled Components
Probably the most powerful and useful in my opinion is Styled Components. Styled Components lets you write actual CSS in your JavaScript. The main advantage is that you can add conditional code and use variables and functions within the CSS!.
You can install Styled Components using the following command:
npm install --save styled-components
Next, you need to import it in you component. Then you can create a new variable that will contain the CSS. The same variable name with open and close brackets will render or create an HTML element with the previously added styles on it.
import styled from 'styled-components'
// Create a button variable and add CSS
const Button = styled.button`
background: transparent;
border-radius: 3px;
border: 2px solid red;
color:red;
`
//display the HTML
render(
<div>
<Button>Button</Button>
</div>
);
Thanks for reading the post!.
Please check out my new tutorial.
And please support me on hubpages as well.
Until next time.
Cheers!
This content originally appeared on DEV Community and was authored by Saleh-Mubashar
Saleh-Mubashar | Sciencx (2021-11-03T03:48:30+00:00) 3 Ways to add CSS in React JS. Retrieved from https://www.scien.cx/2021/11/03/3-ways-to-add-css-in-react-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.