Nishtha Pant
Nishtha Pant

Reputation: 41

How to get the value of the checkbox lable in material-ui?

I am using Checkbox from material UI. This is the import statement:

import Checkbox from '@mui/material/Checkbox';

I have the following code being rendered :

<Checkbox value="Tutor 1" onClick={() => handleSendSelection()}/>

I want to get the value of the selected checkbox inside the handleSendSelection() function. When I print the value, it gives me undefined, whereas my expected value is the string "Tutor 1". How should I get the value of the checkbox?

const handleSendSelection = (event) => {
   console.log("value - ", event.target.value);
}

Upvotes: 4

Views: 10643

Answers (2)

Hameez Rizwan
Hameez Rizwan

Reputation: 326

You did not pass the event in onclick function.

   <Checkbox value="Tutor 1" onClick={(event) => handleSendSelection(event)}/>
    const handleSendSelection = (event) => {
      console.log("value - ", event.target.value);
    }

Here's the working sandbox code https://codesandbox.io/s/checkboxes-material-demo-forked-4xo59?file=/demo.js

Upvotes: 2

Yash Falke
Yash Falke

Reputation: 283

import { useState } from "react";
import "./styles.css";


export default function App() {

  const [value, setValue] = useState("")

  return (
    <div className="App">
      <input type="checkbox" value={value} onChange={() => (setValue("tutor_1"))} />
    </div>
  );
}

You can do something like that try to make an controlled checkbox qand set it according to your choice

Upvotes: 3

Related Questions