3

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>
5
  • 2
    You need this: jsfiddle.net/76zh9os8 (a style object and style={myStyle}) Commented Jul 8, 2021 at 10:25
  • 1
    Why don't you go with "option 1" but make "myStyle" an object, rather than a string? const [myStyle, setStyle] = useState({ border: '...', color: '...' }) and then <div style={ myStyle }> Commented Jul 8, 2021 at 10:25
  • 1
    try this --> myStyle.map(sty => (<div style={sty}>Hello</div>)) Commented Jul 8, 2021 at 10:25
  • Guy thank you so much, all your answers helped me :D! Commented Jul 8, 2021 at 10:35
  • @SarunUK that will render multiple divs, each with just one rule applied to them. Not what OP wants. Commented Jul 8, 2021 at 10:38

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.