Search code examples
javascriptreactjsreact-nativejsxreact-admin

How can I conditionally format the label for a field in react-admin?


I have this code-part in my Edit view:

         <FormTab label="Jellemzok">
             <SelectInput label="Tipus" source="type" choices={[
                 {id: 0, name: "type1"},
                 {id: 1, name: "type2"},
                 {id: 2, name: "type3"},
                 {id: 3, name: "type4"},
                 {id: 4, name: "type5"},
                 {id: 5, name: "type6"},
                 {id: 6, name: "type7"},
                 {id: 7, name: "type8"},
             ]} optionText="name" />
             <TextInput source="data_1" />
             <TextInput source="data_2" />
             <TextInput source="data_3" />
             <TextInput source="data_4" />
             <TextInput source="data_5" />
             <TextInput source="data_6" />
         </FormTab>

I have to label the data fields based on the Type I select above.

So:

if I choose "type1", my label should be:

             <TextInput label="label1" source="data_1" />
             <TextInput label="label2" source="data_2" />
             <TextInput label="label3" source="data_3" />
             <TextInput label="label4" source="data_4" />
             <TextInput label="label5" source="data_5" />
             <TextInput label="label6" source="data_6" />

but if I chose "type6", my label should be like this:

             <TextInput label="this_is_another_label1" source="data_1" />
             <TextInput label="this_is_another_label2" source="data_2" />
             <TextInput label="this_is_another_label3" source="data_3" />
             <TextInput label="this_is_another_label4" source="data_4" />
             <TextInput label="this_is_another_label5" source="data_5" />
             <TextInput label="this_is_another_label6" source="data_6" />

how can I simply do it?


Solution

  • you need to use the FormDataConsumer component:

    <FormDataConsumer> {({ formData }) => { const label = formData.type === 0 ? "label" : "this_is_another_label" return ( <> <TextInput label={label + 1} source="data_1" /> <TextInput label={label + 2} source="data_2" /> <TextInput label={label + 3} source="data_3" /> <TextInput label={label + 4} source="data_4" /> <TextInput label={label + 5} source="data_5" /> <TextInput label={label + 6} source="data_6" /> </> ) }} </FormDataConsumer>