Search code examples
reactjsreact-adminrecompose

Field/Input label based on record in react admin


I'd like part of the record to be included in the label for a BooleanField (and BooleanInput). I'm trying to use WithProps to accomplish this.

If I use

<BooleanField source="FileSystem" label="FileSystem" />

This seems to work just fine. If, instead I try to wrap it

const makeLabel = (props)=>{
    let label = `Filesystem for ${props.record.id}`;

    return {label};
}

const withLabel = withProps(makeLabel);
const BooleanFieldWithLabel = compose(withLabel)((props)=>{
    console.log("props after compose",props);
    return <BooleanField {...props}/>
});

And then use <BooleanFieldWithLabel source="FileSystem" /> It doesn't render any label. I've tried a few different ways and nothing seems to work even though I can see in the console.log that the correct label is in props. What am I doing wrong here?


Solution

  • I have the same question, I cannot display the label base on field's value on "Show" page. From react-admin source code, it seems only I set "addLabel" prop on the direct child of "SimpleShowLayout" or "TabbedShowLayout", then I can see label on my custom field.

    But it is not configurable, I want to show/hide label base on field's value. Do I need to implement my own custom "SimpleShowLayout" or "TabbedShowLayout"? Or is there any better approaches?

    Update my post. I just figure out the solution by implementing an HOC like below. I am wondering is there any better approaches to implement the same feature?

    import React from "react";
        import get from "lodash/get";
        import { TextField, DateField, Labeled } from "react-admin";
    
        const NullableField = WrappedComponent => props => {
          const { record, source } = props;
          const value = get(record, source);
          return value ? (
            <Labeled {...props}>
              <WrappedComponent {...props} />
            </Labeled>
          ) : null;
        };
        const NullableTextField = NullableField(TextField);
        const NullableDateField = NullableField(DateField);
        export { NullableTextField, NullableDateField };