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>
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With