Reputation: 670
I'm following this tutorial to learn about dynamic forms. It uses the input's className with a custom name and the id property.
<input
type="text"
name={ageId}
data-id={idx}
id={ageId}
value={cats[idx].age}
className="age" <-----------------------
/>
To be able to do this in the function that handles changes:
handleChange = (e) => {
....
if (["name", "age"].includes(e.target.className) ) {
let cats = [...this.state.cats]
cats[e.target.dataset.id][e.target.className] = e.target.value.toUpperCase()
....
}
I want to do the same form using Material UI, I've used TextField, Input and InputBase, the id property works but the className property return the following or similar:
"MuiInputBase-input MuiInput-input"
Is there any way to use the className property or another way to acheive the same thing?
Upvotes: 1
Views: 1230
Reputation: 81036
I'm not sure why the tutorial writer decided to use className
for this purpose. Data attributes are a more appropriate thing to use (and the tutorial already uses data-id for the index). You can specify the data attributes on the input by leveraging the inputProps
property of TextField
.
Here is a working example showing this:
import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";
function App() {
const [state, setState] = React.useState({
cats: [{ name: "cat1", age: "2" }, { name: "cat2", age: "5" }],
owner: "Owner's Name"
});
const handleFormChange = e => {
if (["name", "age"].includes(e.target.dataset.fieldType)) {
const newCats = [...state.cats];
newCats[e.target.dataset.id][e.target.dataset.fieldType] = e.target.value;
setState({ ...state, cats: newCats });
} else {
setState({ ...state, [e.target.name]: e.target.value });
}
};
return (
<form onChange={handleFormChange}>
<TextField label="Owner" value={state.owner} name="owner" />
<br />
<br />
<TextField
label="Name 1"
value={state.cats[0].name}
inputProps={{ "data-id": 0, "data-field-type": "name" }}
/>
<TextField
label="Age 1"
value={state.cats[0].age}
inputProps={{ "data-id": 0, "data-field-type": "age" }}
/>
<br />
<br />
<TextField
label="Name 2"
value={state.cats[1].name}
inputProps={{ "data-id": 1, "data-field-type": "name" }}
/>
<TextField
label="Age 2"
value={state.cats[1].age}
inputProps={{ "data-id": 1, "data-field-type": "age" }}
/>
</form>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
My example is hard-coded to two cats to keep it a little simpler, but the change-handling uses the same general approach as the tutorial and would work with a dynamic number of rows.
Relevant references:
Upvotes: 1