DEV Community

Radheshyam Gupta
Radheshyam Gupta

Posted on

3

How do I check/uncheck all checkboxes with a button In React Js using useRef() Hook ?

How do I check/unchecked all checkboxes with a button In React Js using useRef() Hook ?

In this Post, we will learn about how check/unchecked all checkboxes
using useRef() React Hook.

1>App.js

import logo from './logo.svg';
import './App.css';

import { useRef } from 'react';

function App() {

    const ref = useRef([]);

    const checkboxvalue = (e) => {
        console.log(e.target.value)
    }

    const Unchecked = () => {

        console.log(ref.current.length)
        for (let i = 0; i < ref.current.length; i++) {

            ref.current[i].checked = false;
        }

    }
    const Checked = () => {

        console.log(ref.current.length)
        for (let i = 0; i < ref.current.length; i++) {

            ref.current[i].checked = true;
        }

    }

    return (
        <>
            <div style={{ width: '50%', backgroundColor: '#f7f4f3', marginLeft: '150px', marginTop: '100px', padding:'50px 0px 100px 50px' }}>
            <input ref={(element) => { ref.current[0] = element }} value='12' type='checkBox' onChange={checkboxvalue } /> <br />
            <input ref={(element) => { ref.current[1] = element }} value='123' type='checkBox'  onChange={checkboxvalue } /> <br />
            <input ref={(element) => { ref.current[2] = element }} value='1' type='checkBox'    onChange={ checkboxvalue } /> <br />
            <input ref={(element) => { ref.current[3] = element }} value='1234' type='checkBox' onChange={checkboxvalue } /> <br />

            <button style={{ padding: '5px', backgroundColor: 'green', border: 'none', margin:'5px 5px 5px 5px' }}onClick={Unchecked}>Unchecked</button>

            <button style={{ padding: '5px', backgroundColor: 'red', border: 'none', margin: '5px 5px 5px 5px' }} onClick={Checked}>Checked</button>
            </div> 
        </>
);
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Well done! You now have Done this using useRef() React Hook !

Drop some love by liking or commenting ♥

Reference w3schools

Download Source Code from GitHub Repository

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series