2

I want to put "defaultChecked" attribute to JSX input element but the compiler requires me to use spread operator for activeModal state? Why is that? The state is either true or false:

<input name="radio-size"value="small" type="radio" id="small" {**activeModal**?"checked":""} className="modal-content-sizes-form-option"></input>

3
  • Try this <input checked={activeModal}></input> Commented Aug 27, 2021 at 13:34
  • ^ assuming activeModal is a boolean Commented Aug 27, 2021 at 13:41
  • See also: Dynamic attribute in ReactJS Commented Aug 27, 2021 at 13:45

1 Answer 1

5

JSX expects, that if you put an an expression inside {} somewhere that it expects a prop name, then that expression will be ...someObject where someObject contains a props to values mapping.

e.g.

const myObject = { name: "radio-size", value: "small", // etc } <input {...myObject} /> 

It doesn't expect a string of JSX to insert.

If you want to set a boolean prop, then just assign boolean to the prop:

<input checked={activeModal} (your other props) /> 
Sign up to request clarification or add additional context in comments.

2 Comments

What if I want to put a comment in that context?
@Joymaker — Stackoverflow has a feature for asking new questions. Link back to this answer (see the Share link above) if it will help provide context. Read How to Ask and make an attempt before you actually ask the question though. Don't forget to include a minimal reproducible example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.