Octavian Niculescu
Octavian Niculescu

Reputation: 1327

React form - maintaing state when I don't have a fixed value of fields

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

Answers (1)

Arvind_K
Arvind_K

Reputation: 179

  • You need to add a state variable to be passed to the material-UI text field and attach an onchange method to update the value.
  • But since it seems there might be multiple text fields there needs to be an individual state for each of those text fields. Create a function component as below in your file.
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} />;
}
  • After creating the component call it inside the props.fields.map as below,

props.fields.map((field, index) => { 
                    return (
                    <TextFieldWithState
                    key={index}
                    required
                    id="outlined"
                    name={field}
                    label="Nume"
                    placeholder="Scrie"
                    />
                    )
                })
                

Upvotes: 1

Related Questions