eadsjr
eadsjr

Reputation: 721

How to use 'data-' props passed into a React class?

Given the following in my calling JSX component:

<CoolThing data-itemx="Corduroy" data-itemy="Pancakes" />

I want to be able to use these strings in my CoolThing class.

class CoolThing extends Component {
  getStyle() {
    var itemx = this.props.data-itemx;
    var itemy = this.props.data-itemy;

This produces NaN instead of the data strings. I've tried a few other things:

    this.props.dataItemx    // undefined
    this.props.dataitemx    // undefined
    this.props.itemx        // undefined
    this.props.data.itemx   // error accessing itemx of undefined

Running console.log(this.props) shows that data-itemx is present, but I can't access it.

I already read https://facebook.github.io/react/docs/dom-elements.html but it still isn't clear how to make this work.

So how do you do this?

Upvotes: 1

Views: 59

Answers (2)

Mayank Shukla
Mayank Shukla

Reputation: 104369

Props is an object, you are passing the values in props by keys: data-itemx, data-itemy

So those values will be available by the exact same name and use use brackets [] to access the values. Like this:

class CoolThing extends Component {
   getStyle() {
      var itemx = this.props['data-itemx'];
      var itemy = this.props['data-itemy'];
      console.log(itemx, itemy);
      ....

Suggestion: I will suggest you to not use - in properties name, use dataItemx and dataItemy instead of data-itemx, data-itemy.

Check this snippet:

var App = (props) => {
   console.log(props['a-b'])
   return <p>Hello</p>
}

ReactDOM.render(<App a-b='a'/>, 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'/>

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281636

Access it with the use of brackets notation, dot notation doesn't work with -

class CoolThing extends Component {
  getStyle() {
    var itemx = this.props['data-itemx'];
    var itemy = this.props['data-itemy'];

Snippet:

class CoolThing extends React.Component {
  render() {
    console.log(this.props['data-itemx']);
    return (
      <div>Hello World</div>
    )
  }
}
ReactDOM.render(<CoolThing data-itemx="4324"/>, 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"></div>

Upvotes: 1

Related Questions