Inserting data into the style attribute from an object in React
CSS You can also add styles to elements using the style attribute. In this and the next few lessons, we'll look at ways to inline styling.
Now we will not include the styles.css file, but will pass the corresponding values to the style attribute in the form of an object with styles for each tag, which we will write directly in the component file.
So, let's take our component without CSS styles, which we made in the last lesson:
function App() {
return (
<div>
<p>text</p>
<p>text</p>
<p>text</p>
</div>
);
}
Let's create an object with CSS styles for the div in the App.js file before the return command in the class1 variable. Remember that the property names here are written in camelCase notation, and the property values should be enclosed in quotes:
const class1 = {
width: '200px',
border: '2px solid brown',
padding: '10px',
textAlign: 'center'
};
Now let's add the class2 object with styles for the first paragraph:
const class2 = {
color: 'orangered',
fontWeight: 'bold'
}
Object class3 with styles for the second paragraph:
const class3 = {
fontStyle: 'italic',
color: 'brown',
}
And finally class4 for the last one:
const class4 = {
backgroundColor: 'orange',
fontWeight: 'bold',
color: 'white',
}
Now, to apply CSS classes to the component, we will use the style attribute. For the first paragraph, we had a variable class2, let's pass it as a value:
<p style={class2}>text</p>
In a similar way, we will add styles from objects for the remaining tags.
As a result, the component code will look like this:
function App() {
const class1 = {
width: '200px',
border: '2px solid brown',
padding: '10px',
textAlign: 'center',
};
const class2 = {
color: 'orangered',
fontWeight: 'bold',
};
const class3 = {
fontStyle: 'italic',
color: 'brown',
};
const class4 = {
backgroundColor: 'orange',
fontWeight: 'bold',
color: 'white',
};
return (
<div style={class1}>
<p style={class2}>text</p>
<p style={class3}>text</p>
<p style={class4}>text</p>
</div>
);
}
Take the React component you made in the task for the last lesson, create objects with CSS styles for your tags, put them in the corresponding attributes style.