Home > database >  How to set a color variable in React JS
How to set a color variable in React JS

Time:10-18

I have an array of colors from which i generate a random color to style the text color, background color, etc. Now, want to use that particular color to design my elements. How do i do that.

We basically do this to make a heading red

const element = <h1 style={{ color: 'red' }}>Hello world</h1>

But I want to do something like this (this is wrong code its just for explaining my problem)

const colorvar="red"
const element = <h1 style={{ color: {colorvar} }}>Hello world</h1>

please help me with a solution.

CodePudding user response:

The style prop is an object containing key value pairs of styles (e.g. color, margin):

const style = { color: colorvar }
<div style={style} />

The issue in your code is that you wrap colorvar in brackets, resulting in:

const style = { color: { colorvar: colorvar } }

CodePudding user response:

You should not wrap the variable with curly braces.

This will work.

const element = <h1 style={{ color: colorvar }}>Hello world</h1>
  • Related