Add custom parameter to custom component "components" attribute

Viewed 157

In the Slider example of Material UI (link to codesandbox: https://codesandbox.io/s/hzhqj?file=/demo.tsx), there is an option to pass custom components if you want to use a different subcomponent for a maincomponent.

      <Slider
        valueLabelDisplay="auto"
        components={{
          ValueLabel: ValueLabelComponent,
        }}
        aria-label="custom thumb label"
        defaultValue={20}
      />

By default, Material UI passes 'props' to ValueLabelComponent, so essentially this:

ValueLabel: (props) => ValueLabelComponent(props)

I would like to pass additional data, a simple variable, to this. The custom component can already take a second parameter (ValueLabelComponent(props, additionalData))

How to pass additional parameters to the custom component in this structure?

(Note: I tried this, but it won't work of course: ValueLabel: (props, additionalData) => ValueLabelComponent(props, additionalData))

1 Answers

There are three ways of doing it:

1. Using .bind method

<Slider
  valueLabelDisplay="auto"
  components={{
    ValueLabel: ValueLabelComponent.bind(null, 'test'),
  }}
  aria-label="custom thumb label"
  defaultValue={20}
/>

And then you can access your passed data like:

function ValueLabelComponent(data: any, props: Props) {
  console.log(data); // contains a string 'test'

  // other work here
}

2. Using arrow function

<Slider
  valueLabelDisplay="auto"
  components={{
    ValueLabel: (props) => ValueLabelComponent("test", props),
  }}
  aria-label="custom thumb label"
  defaultValue={20}
/>

3. Render and pass data in props

<Slider
  valueLabelDisplay="auto"
  components={{
    ValueLabel: (props) => <ValueLabelComponent {...props} testProp="test" />,
  }}
  aria-label="custom thumb label"
  defaultValue={20}
/>

And then you can access your passed data like:

function ValueLabelComponent(props: Props) {
  console.log(props.testProp); // contains a string 'test'

  // other work here
}
Related