简体   繁体   中英

Check all checkboxes, and uncheck if any of them deselected in React without jQuery

I would like to select all checkboxes . But if user deselect any checkbox, i want also uncheck "select all" checkbox.

In given example below, How can achieve this?

Live Demo : https://react-f3tcbc.stackblitz.io

Live Editor : https://stackblitz.com/edit/react-f3tcbc

Some samples I looked refer checked as boolean parameter in items . However my items object comes from ajax response as json and they have no value such as checked .

I want to do this in React way. Not jQuery. Any ideas?

One way of going about it is to add an extra property called eg isChecked to the data you get from the network request, and use that to control all the checkboxes.

Example

 const posts = [ { id: 1, name: "Text 1" }, { id: 2, name: "Text 2" }, { id: 3, name: "Text 3" } ]; class App extends React.Component { state = { name: "React", posts: [], isAllChecked: false }; componentDidMount() { setTimeout(() => { this.setState({ posts: posts.map(post => ({ ...post, isChecked: false })) }); }, 1000); } handleSelect = id => { this.setState(prevState => { const posts = prevState.posts.map(post => post.id === id ? { ...post, isChecked: !post.isChecked } : post ); const isAllChecked = posts.every(post => post.isChecked); return { posts, isAllChecked }; }); }; handleSelectAll = () => { this.setState(prevState => { const isAllChecked = !prevState.isAllChecked; const posts = prevState.posts.map(post => ({ ...post, isChecked: isAllChecked })); return { posts, isAllChecked }; }); }; render() { const { posts, isAllChecked } = this.state; return ( <div> {posts.map(fx => ( <TableItem key={fx.id} id={fx.id} name={fx.name} checked={fx.isChecked} onChange={() => this.handleSelect(fx.id)} /> ))} <div> <label> <input type="checkbox" checked={isAllChecked} onChange={this.handleSelectAll} /> Select all </label> </div> </div> ); } } class TableItem extends React.Component { render() { const { checked, onChange, name } = this.props; return ( <tr> <td> <input type="checkbox" checked={checked} onChange={onChange} /> </td> <td>{name}</td> </tr> ); } } ReactDOM.render(<App />, document.getElementById("root")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM