⊗jsrtPmSyVTS 102 of 112 menu

Inserting data into the style attribute from variables in React

In the previous lesson we wrote the object directly in the style attribute. We can also use inserting data into this object from variables.

Let's take our React component without CSS styles:

function App() { return ( <div> <p>text</p> <p>text</p> <p>text</p> </div> ); }

Now we will create variables and assign CSS property values ​​to them. Let's start in order with the styles for the div.

In the component file, before the return command, create a variable wd1 and assign it the value '200px':

const wd1 = '200px';

In a similar way, we will create variables for all the property values ​​of our div:

const wd1 = '200px'; const br1 = '2px solid brown'; const pd1 = '10px'; const ta1 = 'center';

Now let's add variables for the first paragraph:

const co1 = 'orangered'; const fw1 = 'bold';

For the second paragraph:

const fs1 = 'italic'; const co2 = 'brown';

And finally, for the last one. Here we only need two variables, not three. There is no point in repeating ourselves, because we already have the value bold for the first paragraph:

const bco1 = 'orange'; const co3 = 'white';

Now we'll substitute variables with style values. Let's do this for the first paragraph. Let's insert variables co1 and fw1 instead of the values ​​in the object:

<p style = {{ color: co1, fontWeight: fw1 }}> text </p>

We will do the same with the remaining tags.

As a result, our component code will look like this:

function App() { //for div: const wd1 = '200px'; const br1 = '2px solid brown'; const pd1 = '10px'; const ta1 = 'center'; //for the first p: const co1 = 'orangered'; const fw1 = 'bold'; //for the second p: const fs1 = 'italic'; const co2 = 'brown'; //for the third p: const bco1 = 'orange'; const co3 = 'white'; return ( <div style = {{ width: wd1, border: br1, padding: pd1, textAlign: ta1 }}> <p style = {{ color: co1, fontWeight: fw1 }}> text </p> <p style = {{ fontStyle: fs1, color: co2 }}> text </p> <p style = {{ backgroundColor: bco1, fontWeight: fw1, color: co3 }}> text </p> </div> ); }

Modify the code from the previous lesson so that the CSS property values ​​are stored in variables.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline