Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly pass custom data attribute props to child components?

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'/>
like image 507
Joshua Rajandiran Avatar asked Aug 03 '16 09:08

Joshua Rajandiran


People also ask

How do you pass props to a child component?

There is no way to pass props up to a parent component from a child component. We will revisit this caveat later in this tutorial. It's also important to note that React's props are read only (immutable). As a developer, you should never mutate props but only read them in your components.

How do I pass props from parent to child in Vue?

The way it works is that you define your data on the parent component and give it a value, then you go to the child component that needs that data and pass the value to a prop attribute so the data becomes a property in the child component. You can use the root component (App.


1 Answers

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" />
like image 110
Serhii Baraniuk Avatar answered Sep 28 '22 01:09

Serhii Baraniuk