I have a Create form where another SelectInput is made visible depending on the selection of another SelectInput.
The first time this happens, the first input is cleared. How do I stop the first select from clearing?

Here is the code to recreate:
import {Create, SelectInput, TextInput, SimpleForm} from 'react-admin';
import React from 'react';
class Recreate extends React.Component {
constructor(props) {
super(props);
this.props = props;
this.state = {visible: false}
}
render() {
return (
<Create {...this.props}>
<SimpleForm>
<SelectInput source="device" choices={[{id: 'OR', name: 'Oregon'}, {id: 'WA', name: 'Washington'}]}
onChange={(event, key, payload) => this.setState({visible: key === 'WA'})}
/>
{this.state.visible && (
<SelectInput label={'I am visible from WA'}
source="renderer"
choices={[
{id: 'Seattle', name: 'Seattle'},
{id: 'Olympia', name: 'Olympia'},
]}
defaultValue={'gs'}/>
)}
</SimpleForm>
</Create>
);
}
}
export default Recreate;
Update: Attempted fix based on answers:
import {Create, SelectInput, SimpleForm, TextInput} from 'react-admin';
import React from 'react';
const CustomSelectInput = ({onChangeCustomHandler, ...rest}) => (
<SelectInput onChange={(event, key, payload) => {
onChangeCustomHandler(key)
}}
{...rest}
/>
);
class Recreate extends React.Component {
constructor(props) {
super(props);
this.props = props;
this.state = {visible: false}
}
render() {
return (
<Create {...this.props}>
<SimpleForm>
<CustomSelectInput source="device"
choices={[{id: 'OR', name: 'Oregon'}, {id: 'WA', name: 'Washington'}]}
onChangeCustomHandler={(key) => this.setState({visible: key === 'WA'})}/>
{this.state.visible && (
<SelectInput label={'I am visible from WA'}
source="renderer"
choices={[
{id: 'Seattle', name: 'Seattle'},
{id: 'Olympia', name: 'Olympia'},
]}
/>
)}
</SimpleForm>
</Create>
);
}
}
export default Recreate;
The first input is cleared probably because you override its onChange prop without calling the original one which is injected transparently by SimpleForm.
You'll need to introduce a custom SelectDeviceInput component which will wrap the original SelectInput, handle its onChange event and call another onXXX prop you can pass in the same handle. Set your state in the handler you'll pass to this onXXX prop inside the Recreate component.
NOTE: Your custom SelectDeviceInput will receive an input prop with the onChange handler you must call for redux-form to work. See https://redux-form.com/7.4.2/docs/api/field.md/#1-a-component
That's one side effect of SimpleForm doing a cloneElement of its children to ease its usage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With