1

I'm trying to build a form with radius being the options generated by a mapped array, but the following error appears:

Uncaught Error: input is a void element tag and must neither have children nor use dangerouslySetInnerHTML.

The code below goes into rendering a component React:

<form>
    <p>{this.state.current_statement}</p>
    <div>
        {this.state.current_alternative.map(item => (
            <input key={item.id} type="radio">
                <label>{item.content}</label>
            </input>
        ))}
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</form>

1 Answer 1

3

input is a void element tag

<input> elements are not allowed to have children. You have put the <label> element into the input. React complains about that because it is not allowed although the browser may display it anyways. You need to render the label next to the input instead of inside it:

{this.state.current_alternative.map(item => (
     <React.Fragment>
         <label htmlFor={item.id}>{item.content}</label>
         <input name="someName" key={item.id} id={item.id} type="radio" />
     </React.Fragment>
))}

To do this you need to wrap the elements returned by the map() callback either into a Fragment or a container component like a <div>. The reason for that is that the callback must return a single value, e.g. a single node which you can achieve with Fragment.

To associate the label with the input assign an id to the input and set the htmlFor prop on the label.

Sign up to request clarification or add additional context in comments.

5 Comments

The following error appears, but when I put <div key = {item.id}> </ div> I can select all the options: Unexpected token <. Remember, adjacent JSX elements must be wrapped in an enclosing parent tag
React Fragment worked, but it selected all the elements
@HiagoBonamelli The spaces between prop name and value are not valid syntax. It has to be key={item.id}. The same goes for </div>. You can't place arbitrary whitespaces in jsx.
worked, but I can select all the elements, do you know why?
@HiagoBonamelli Mutually exclusive options need to have the same name assigned to the name prop. Read this.

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.