mardi 7 mars 2023

Checkboxes in React MUI stop working after applying an inital state

So I'm loading a todo list from a json. It looks something like this:

{ 
"todos": [
{"id":1,"todo":"Do something nice for someone I care about","completed":true,"userId":26},{"id":2,"todo":"Memorize the fifty states and their capitals","completed":false,"userId":48},{"id":3,"todo":"Watch a classic movie","completed":false,"userId":4}
] ,"total":150,"skip":0,"limit":30 
} 

So when I load it and apply the "completed" to the Checkbox checked the checkbox stops working. Absolutely nothing happens when I click it.

Code:

import './App.css';
import React, { Component }  from 'react';
import { Checkbox, FormControlLabel, FormGroup } from '@mui/material';

import data from './todo-list.json';

function App() {
  return (
    <div>
      <header>
        <FormGroup>
          {data.todos.map(todo => <FormControlLabel control={<Checkbox checked={todo.completed}
        
          />} label={todo.todo} /> )}
        </FormGroup>
      </header>
    </div>
  );
}

export default App;

I also get a warning Warning: Each child in a list should have a unique "key" prop..

I tried doing something like this:

  const [isTrue, setIsTrue] = React.useState(false);
  
  return (
    <div>
      <header>
        <FormGroup>
          {data.todos.map(todo => <FormControlLabel control={<Checkbox
          checked={isTrue}
        onChange={e=> {
          setIsTrue(e.target.checked)
        }}
          />} label={todo.todo} /> )}
        </FormGroup>
      </header>
    </div>
  );

But this doesn't apply the initial state and also when I click the checkbox it clicks all the checkboxes. So my click is applied to all of the checkboxes on the screen.




Aucun commentaire:

Enregistrer un commentaire