How to properly pass custom data attribute props to child components?
Asked Answered
W

3

11

Basically I have 3 custom attributes data-pageName, data-defaultOption, data-options.

The problem I have is that when I pass into my child component I get an unexpected token error because its something like this:

const pageContent = ({data-pageName, name, onChange, data-defaultOption, value, data-options}) => {
/*return here*/
};

Basically the - symbol is causing the error.

How do I include it as data-pageName and not read as data - pageName?

This is how I call the component:

<pageContent data-pageName={this.state.pageClicked} onChange={this.closeMenu} data-defaultOption={this.state.tmpDefaultOption} value={this.state.tmpValue} data-error={this.state.tmpError} data-options='a'/>
Whorish answered 3/8, 2016 at 9:53 Comment(1)
How do you call pageContent?Farmhand
S
12

Dashes are not allowed in variable names. So, you have to use quotes ''

const Example = (props) =>
  <div>{props['data-name']}</div>

ReactDOM.render(
  <Example data-name="hello"/>,
  document.getElementById('app')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app" />
Sulfuric answered 3/8, 2016 at 9:58 Comment(0)
A
8

When you destruct your child component props, you can assign its dashed variables to variables with new names.

const PageContent = ({ 'data-options': dataOptions }) => (
    <div>...</div>
);

PageContent.propTypes = {
    'data-options': PropTypes.string
};
Alfie answered 3/6, 2019 at 19:57 Comment(1)
Exactly what I was looking for, thanks for the answer!Claudication
C
3

When using dashes, you must wrap it inside single quotes.

render() { 
  const myProps = {
    'data-pageName': this.state.pageClicked,
    'data-defaultOption': this.state.tmpDefaultOption,
  };

  return <MyComponent {...myProps} />
}

You can then use this.props['data-pageName'] inside your child component.

Collinear answered 3/8, 2016 at 12:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.