What does it mean {...a11yProps(0)} in the component property?

Viewed 5029

Consider the following code snippet of a component:

...
...

function a11yProps(index: any) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}

...
...

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Tabs value={value} onChange={handleChange} aria-label="simple tabs example">
          <Tab label="Item One" {...a11yProps(0)} />
          <Tab label="Item Two" {...a11yProps(1)} />
          <Tab label="Item Three" {...a11yProps(2)} />
        </Tabs>
      </AppBar>
      <TabPanel value={value} index={0}>
        Item One
      </TabPanel>
      <TabPanel value={value} index={1}>
        Item Two
      </TabPanel>
      <TabPanel value={value} index={2}>
        Item Three
      </TabPanel>
    </div>
  );
}

I struggle to understand the following component implementation:

<Tab label="Item One" {...a11yProps(0)} />

What does {...a11yProps(0)} mean? Does it mean I pass here properties?

When I look at the API documentation of Tab, I can not find the id and aria-controls properties.

The whole code https://codesandbox.io/s/kz25m

2 Answers

It is a spread operator (... is Javascript spread operator). It basically de-structures / spreads out the value from an array or object.

In your sample code I see your function returns some javascript object. This spread operator pulls out / de-structures all the values from the object and gives each individual values as output

{... a11yProps(0)} 
==> This would return -> {...{id: `simple-tab-0`,aria-controls: `simple-tabpanel-0`}} 
==> on spreading out the values from the object it would look like 
=> {id: `simple-tab-0`,aria-controls: `simple-tabpanel-0`}

Another example with spread operator

let d = {...{"a":1, "b":2, "c":3}}


output: {a: 1, b: 2, c: 3}

Please refer to ES6 website for more on spread operator, destructuring - http://es6-features.org/#SpreadOperator

It's just a function for making a dynamic object and using them as props, to reduce code size.

<Tab label="Item One" id="simple-tab-0" ariaControls="simple-tabpanel-0"/>

About TypeScript and Docs: If you ctrl + click on the Material-UI component, you can see they extends types of component with React.ElementType and inside of this, you can find JSX.IntrinsicElements and each one of HTML element has React.DetailedHTMLProps with props of HTMLAttributes extended with AriaAttributes and DOMAttributes. So naturally, you can pass all of the available attributes for that tag on them!

Related