Styling with React components
Day 11 of #100DaysOfCode
Today we will learn how to style our HTML with React components.
The HTML code for our page will be:
We have a div with the id root, a script tag of React, Reactdom, and Babel.
Our CSS code will be:
Our JS code will look like this:
We have rootElement
, which takes our div with the id root
, and variable element
, which displays a div with text small box. Finally, in rootElement
, we render our element
.
Now, let’s give the div a class and some inline styling like:
If you run this code, you should see something similar to this:
Let’s add two additional divs now.
It will display something similar to:
If you look at variable elements
, you will notice that many of them are repetitive, such as class named box
, etc. For this, you can use a react component. Let us create a component.
Here we have a Box component
that accepts the prop objects className, style, and rest
. It returns a div with a className box
and any other classNames we specify. Style with fontStyle as italic
and any extra styles we may give Finally, rest
provides any further attributes that we supply to our div.
You will also need to modify the JSX code:
We are using our function component Box
instead of a div tag
. The result will be the same as previously.
That’s all for now.