Hassan Turi
Hassan Turi

Reputation: 354

How to use map function with checkbox in ReactJS?

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>

Upvotes: 1

Views: 6088

Answers (5)

Omor Faruk
Omor Faruk

Reputation: 67

You should use return keyword or implicitly return

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

Upvotes: 1

Adam Foody
Adam Foody

Reputation: 19

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>

   );
 }

Upvotes: 1

Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

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>

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196306

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>

Upvotes: 3

Evren
Evren

Reputation: 4410

You should change curly braces with parentheses

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

Upvotes: 1

Related Questions