I have a react-component that acts as a container for multiple text-fields. Initially there’s just a single textbox, however the user can dynamically add more.
So I have a model for every textfield:
interface TextFieldProps
{
value: string,
setValue: (newValue: string) => void
}
which is used in my MyTextField
-component:
function MyTextField(props: TextFieldProps) => {
return (<TextField value={props.value} onChange={props.setValue} />)
}
As you can see MyTextField
is just a wrapper around a MUI-textbox. When the onChange
-event on that textbox is triggered, the setValue
-function passed to my wrapper is executed. This way I can grab the textbox’s values inside my cntainer and also call some code whenever one of the textboxes changes.
So finally here’s the Container
-component
function Container() => {
const[textFields, setTextFields] = useState<TextFieldProps>[]();
return(
<>
{
textFields.map(t => <MyTextField value={ t.value } setValue={ t.setValue } />
}
</>
)
}
However I have no idea how to create an instance of the TextFieldProps
in order to build new wrapper-components from them.
What I want to achieve is have my container access to the containing textbox-values and their setter-functions.
2
Answers
To achieve this, you can manage the state of text fields as an array of objects in your Container component. Each object will have a value and an id to uniquely identify each text field (for example, the date created, or the index, or the guuid, whatever), ensuring the state updates independently. Please take a look at sandbox here
Define the Text Field Component
Create a wrapper around the MUI TextField that takes value and setValue as props.
Define the Container Component
In the Container component, manage the state as an array of objects. Each object will hold a value and an id.
Explanation
a value and a unique id. The id ensures each text field is
independently managed.
addTextField
function adds a new object to the state array.updateTextField
function updates a specific text field’s valueusing its id.
In order to control multiple textboxes at a time, one way to do it is to have a
useState
in which you have a map wherekey
is a unique key of a text field andvalue
is the value of the input.Then, you can use your array of textboxes (eg.
['firstName', 'lastName', 'address1', 'address2']
) and map theMyTextField
retrieving text field value by its key and setter function by themakeHandleChange
factory.This way, you can easily access textboxes’ values and adjust the factory function to your business logic.
Without
makeHandleChange
factory: