Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep and loop the style of HTML element from an Array in REACT?

I am creating a form builder, so one of my requirements is users should be able to add style. So far these are the options I tried but it's not working

Option 1

State 1

const [myStyle, setStyle] = useState("border: '2px solid red', color: 'yellow'")

Element 1

<div style={{myStyle}}>Hello First Trial</div>

Option 2

state 2

const [myStyle, setStyle] = useState([
     {name: 'border', value:'2px solid red'},
     {name: 'color', value:'yellow'} 
])

Element 2

<div style={{myStyle.map(style=> {
                     return {style.name:style.value}}}>
                    Hello Second Trial
</div>
like image 285
nasiphi vinqishe Avatar asked Dec 05 '25 20:12

nasiphi vinqishe


2 Answers

use this one it works fine

const [myStyle, setStyle] = useState({border: '2px solid red', color: 'yellow'})

and

<div style={myStyle}>Hello First  Trial</div></div>
like image 82
TinsG Avatar answered Dec 08 '25 09:12

TinsG


Option 1:-

const [myStyle, setStyle] = useState({border: '2px solid red', color: 'yellow'})

<div style={myStyle}>Hello First  Trial</div></div>

Option 2:-

const [myStyle, setStyle] = useState([
     {name: 'border', value:'2px solid red'},
     {name: 'color', value:'yellow'} 
])

Use reduce method to prepare a single object out of the array.

    <div
    style={myStyle?.reduce((agg, val) => {
      agg[val.name] = val.value;
      return agg;
    }, {})}
  >
    Hello Second Trial
  </div>

Codesandbox - https://codesandbox.io/s/epic-wildflower-sutkr?file=/src/App.js:294-495

like image 41
Sarun UK Avatar answered Dec 08 '25 09:12

Sarun UK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!