'React Custom Attributes from Event Object Show Up as Undefined
I am a beginner learning React and have been trying to create two TextField's with MUI where I have two strings in the state to store the subject and number both as strings. I want to use one function to change the state of either the subject or number based on which TextField is changed. I created a custom attribute called data-id in each TextField and called console.log(event.target.dataset.id); within my handleSearchChange(event){...} function. For some reason each time I type a value into either TextField it just says undefined in the console.
Some resources I have tried
https://reactjs.org/docs/events.html
https://www.pluralsight.com/guides/how-to-access-custom-attributes-from-aevent-object-in-react
https://www.codegrepper.com/code-examples/javascript/react+get+data+attribute+from+element
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { TextField } from '@mui/material';
class ClassSearch extends React.Component {
constructor(props) {
super(props);
this.handleSearchChange = this.handleSearchChange.bind(this);
};
handleSearchChange(event){
console.log(event.target.dataset.id);
}
render() {
return(
<div>
<h1>Classes Search</h1>
<TextField
onChange={this.handleSearchChange}
data-id = "subject"
type = "search"
id="outlined-basic"
variant="outlined"
/>
<TextField
onChange={this.handleSearchChange}
data-id = "number"
type = "search"
id="outlined-basic"
variant="outlined"
defaultValue={this.state.number}
/>
</div>
);
}
}
ReactDOM.render(
<React.StrictMode>
<ClassSearch />
</React.StrictMode>,
document.getElementById('root')
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
