1

I want to use the map function with the checkbox. I have written this code but it is giving error. how to do that

<div>
  <form>
   {
     data.map((x)=>{
     <input type="checkbox" />{x.name}
     }) 
     }
   </form>
 </div>

5 Answers 5

3

You need to return from the map callback

<div>
  <form>
   {
     data.map((x) => {
       return <input type="checkbox" />{x.name}
     }) 
   }
  </form>
</div>

and you could also add a label around the input and text, so that the user can also click on the text to highlight the relevant checkbox

<div>
  <form>
   {
     data.map((x) => {
       return <label><input type="checkbox" />{x.name}</label>
     }) 
   }
  </form>
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

When using arrow functions in JavaScript, you can return either explicitly or implicitly.

Explicitly

<div>
  <form>
     {
       data.map(x => {return <input type="checkbox" />{x.name}})
     }
   </form>
 </div>

Implicitly

<div>
  <form>
     {
       data.map(x => <input type="checkbox" />{x.name})
     }
   </form>
 </div>

Doing the following will cause data.map(x => {<input type="checkbox" />{x.name}}) to be an array of undefined instead of an array of inputs.

<div>
  <form>
     {
       data.map(x => {<input type="checkbox" />{x.name}})
     }
   </form>
 </div>

Comments

1

You should change curly braces with parentheses

<div>
  <form>
   {
     data.map((x)=>(
        <input type="checkbox" />{x.name}
     ) 
     }
   </form>
 </div>

Comments

1

Now that you've been helped with the checkbox syntax, I would suggest using keys when using map.

If you do not have a unique value for each item, add an index parameter in the callback function.

 import React from "react";
 import "./style.css";

  export default function App() {

    const list = [1,2,3,4,5];

   return (
       <div>
        <ol>
        {list.map((item, index) => 
          <li key={index}> {item} </li>
        )} 
      </ol>
      </div>

   );
 }

Comments

1

You should use return keyword or implicitly return

<div>
  <form>
   {
     data.map(x=> (
     <input type="checkbox" />{x.name}
    )) 
   }
   </form>
</div>

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.