This question is to understand which is the best option out of many to get a form data with multiple inputs. i have read many blogs and stackoverflow answers, still not satisfied with the results.
I have a component with a filter form having n number of input fields. in the same components, there is a table which displays the data as per the filters.
First method i tried, is updating n states on changes of n input fields. this is re-rendering the whole component. (it is unnecessary since i need to filter only when the filter button is clicked)
second method, created a controlled input component and in parent component under forms added it as child. now changes in input fields are only updated in that component. when filter button in parent component is clicked, i use ref to get the input field data.
Parent component
const formRef = useRef()
const handleFilter= () =>{
//here all i need to do is get the input data..no dom modification
console.log(formRef.current.a.value)
console.log(formRef.current.b.value)
console.log(formRef.current.c.value)
//call the api to get the data based on above queries and display in the table
}
<parent>
<Form ref={formRef}>
<CustomInput input name='a'/>
<CustomInput input name='b'/>
<CustomInput input name='c'/>
<Button onClick={handleFilter}> Filter </Button>
</Form>
<Table >
Data displayed as per above form filter only when filter button clicked
</Table>
</parent>
Child component ( CustomInput ):
const CustomInput = (props) =>{
const [value, setValue] = useState('')
return(
<input name={props.name}
value={value}
onChange = {(e) => setValue(e.target.value)}/>
)
}
third method to stop full component re-rendering is : Make
Form as a separate component, in that call theCustomChildinput component and call the Form component inparent. here i would have to lift up the state two levelsi can use context hook or redux or whatever tool is available.
Out of these 4 , i found method 2 is less code, easy to understand and maintain.
So can i go with it ?. does this implementation follow the react rules (although this 2nd method helps me to reduce the re-render to only one input component at a time ) ?
Or is there a better way than this ? All opinions are welcomed