Home > Software engineering >  How to use map function with checkbox in ReactJS?
How to use map function with checkbox in ReactJS?

Time:04-21

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>

CodePudding user response:

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>

CodePudding user response:

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>

CodePudding user response:

You should change curly braces with parentheses

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

CodePudding user response:

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>

   );
 }
  • Related