Search code examples
reactjsinputbindreact-adminstateless

How to bind a Stateless Component Input to other Inputs in react-admin's views


Having read an official doc here, I come across these statements

...the <Field> component can access the current record via its context. The name prop serves as a selector for the record property to edit.

Then, I try to make sense of the statements by this experiment:

const CustomInput1 = () => (
     <span>
         <Field name="title" component="input" />
     </span>
);

export const PostCreate = (props) => (
    <Create {...props}>
        <SimpleForm>
            <TextInput source="title" />
            <CustomInput1/>
        </SimpleForm>
    </Create>
);

It turns out that Field's prop name and TextInput's prop source are bound together, in the sense that whenever I make any change in one input, the value of another input also changes accordingly.

My question is. Why is it not possible to reproduce the same effect by using a Stateless Component like this?

const CustomInput2 = ({ record, source }) => (
  <input type="text" value={record[source]}/>;
);
export const PostCreate = (props) => (
    <Create {...props}>
        <SimpleForm>
            <TextInput source="title" />
            <CustomInput2 source="title"/>
        </SimpleForm>
    </Create>
);

From what I understand, both two inputs in the latter case bind to record['title'] and they share the same record object, aren't they?

The actual reason I do this is that I want to change all other input's values based on an update of one single input. My naive understanding is that this can be achieved through a shared record.


Solution

  • so will not work, to solve your problem use FormDataConsumer:

    https://marmelab.com/react-admin/Inputs.html#linking-two-inputs