Max
Max

Reputation: 13334

How to access record inside Edit function without having to use <SimpleForm>?

I have a <Ressource> declared as follows in App.tsx:

<Resource name="myresource" list={ListGuesser} edit={GenericEdit}/>

The code for GenericEdit:

const GenericEdit = function (props) {
    console.log('props', props);
    console.log('useResourceContext()', useResourceContext());
    console.log('useRecordContext()', useRecordContext());
    return (
        <>
            <Edit {...props}>
                <SimpleForm>
                    <TextInput disabled label="Id" source="id" />
                    <TextInput label="Name" source="name" />
                </SimpleForm>
            </Edit>
        </>)
};
export default GenericEdit;

The <Edit><SimpleForm> default setup works well (ie the record data is rendered inside the form), however I'd like to be able to use the record data my own way:


Q: How can I access the record data within my edit function (GenericEdit) without having to rely on the default <SimpleForm> functionality?

Upvotes: 2

Views: 2644

Answers (2)

Max
Max

Reputation: 13334

Answer from React admin support, which works for me:

The Edit component fetches the data and passes it to its children. In order to access fetch data, you would have to add an intermediate component and use the useRecordContext hook.

const MyForm = props => {
    const record = useRecordContext(props);
    console.log({ record });
    return (
        <>
            {/* We can still use the built-in React Admin */}
            <SimpleForm {...props}>
                <TextInput source="id" />
            </SimpleForm>
            {/* Or use something custom */}
            <div>{JSON.stringify(record)}</div>
        </>
    );
};

const GenericEdit = props => (
    // Here, the data hasn't been fetched yet 
    <Edit {...props} >
        <MyForm />
    </Edit>
);
export default GenericEdit;

Upvotes: 6

MaxAlex
MaxAlex

Reputation: 3319

You can use the source code of the Edit and EditView components to implement your form display. In the source text, you can see that it is Edit that provides the transfer of record data: Edit.tsx, EditView.tsx

export const Edit = ( props: EditProps & { children: ReactElement } ): ReactElement => {

    useCheckMinimumRequiredProps('Edit', ['children'], props);
    const controllerProps = useEditController(props);

    const body = (
        <EditContextProvider value={controllerProps}>       
            <EditView {...props} {...controllerProps} /> // Your component for displaying form            
        </EditContextProvider>
    );

    return props.resource ? (
        // support resource override via props
        <ResourceContextProvider value={props.resource}>
            {body}
        </ResourceContextProvider>
    ) : (
        body
    );
};         


   

Upvotes: 0

Related Questions