Use React children props
September 30, 2022 - 1 minute readLet's imagine you have a component <FormWrapper> that stores some specific value e.g. to display additional fields:
1const FormWrapper = () => { 2 const [showExtraFields, useShowExtraFields] = useState(false); 3 4 return ( 5 <form> 6 <Inputs/> 7 {!!showExtraFeilds && <ExtraInputs/>} 8 </form> 9 ) 10} 11
It works as expected however there's one tricky part. Whenever the showExtraFields value changes, the Inputs component rerenders. This is what the FromWrapper component looks like after pure js transpilation
1const FormWrapper = () => { 2 const [showExtraFields, useShowExtraFields] = useState(false); 3 return React.createElement("form", null, React.createElement(Inputs, null), 4 !!showExtraFields && React.createElement(ExtraInputs, null)); 5}; 6
Whenever the parent component rerenders, React.createElement(Inputs, null) is called and it creates an object: { type: Inputs, props: {} } what forces Intpus to rerender as well (since props object's reference has changed). Although if you use the children prop, the issue is gone. It's because React has the "bailout" mechanism for preventing rendering children components.
That's how the FormWrapper looks with the prop:
1const FormWrapper2 = props => { 2 const [showExtraFields, useShowExtraFields] = useState(false); 3 return React.createElement("form", null, props.children, 4 !!showExtraFields && React.createElement(ExtraInputs, null)); 5}; 6
As you can see, the children are passed to the form however there's no createElement for them.