Reputation: 1327
So I created a component which is responsible with opening a form to add data. Here it is:
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import { useState } from "react";
import "./CreateRow.css";
type Props = {
fields: string[]
}
export default function CreateRow(props: Props) {
function sendData(event: any) {
event.preventDefault();
console.log(event);
}
const [creatingRow, setCreatingRow] = useState(false);
return (
<>
<Button variant="contained"
onClick={() => setCreatingRow(!creatingRow)}
className="adauga-button"
>Adauga</Button>
{
creatingRow && (
<form onSubmit={sendData} className="create-form">
{
props.fields.map((field, index) =>
{
return (
<TextField
key={index}
required
id="outlined"
name={field}
label="Nume"
placeholder="Scrie"
/>
)
}
)
}
<Button variant="contained"
className="trimite-button"
>Finalizeaza</Button>
</form>
)
}
</>
);
}
the fields that will be rendered for the form, will be passed as props, in a string array (as you can see)
So how will I create my hooks for controlling the form data?
Upvotes: 0
Views: 37
Reputation: 179
function TextFieldWithState(props) {
const [value, setValue] = useState(props?.value ? props.value : ""); //checking if value is there in props if so assigning it else
const updateValue = (e) => setValue(e.target.value);//function to update the state value.
return <TextField {...props} value={value} onChange={updateValue} />;
}
props.fields.map((field, index) => {
return (
<TextFieldWithState
key={index}
required
id="outlined"
name={field}
label="Nume"
placeholder="Scrie"
/>
)
})
Upvotes: 1