1

I'm using react 16.0.

I want to assign a custom object property to an element and get its value.

It is as follows. (https://jsfiddle.net/69z2wepo/96660/) Of course it does not work.

class Test extends React.PureComponent {
    render () {
        let numbers = { number:1, number2:2, number3:3 };
        return <div numbers={numbers} onClick={(event) => console.log(event.target.numbers.number)}>Test</div>;
    }
}

ReactDOM.render(
  <Test/>, document.querySelector('body')
);

I want to know if there is a good way. Thanks.

left click
  • 894
  • 10
  • 21
  • 2
    you can use `data-*` attributes and pass in a string. but why would you want to do that? why not creating a component and pass props? this is how react meant to work – Sagiv b.g Dec 30 '17 at 12:12
  • 1
    If your purpose of doing it is to avoid binding inside render, then you could take a look at this https://stackoverflow.com/questions/45053622/how-to-avoid-binding-inside-render-method/45053753#45053753 – Shubham Khatri Dec 30 '17 at 12:26
  • DOM travel is expensive, not to mention that you break react's pattern and you can interrupt with its [diffing and Reconciliation algorithm](https://reactjs.org/docs/reconciliation.html). the virtual DOM is used for a good reason :) – Sagiv b.g Dec 30 '17 at 12:27
  • It was helpful. Thank you guys – left click Dec 30 '17 at 12:37
  • Objects or array are converted to strings using toString method resulting in `[object object]` being passed for object and hence passing them on to the div directly will mean, you need to stringify and pass it, which is a overhead, Please check the linked answer for a solution – Shubham Khatri Dec 30 '17 at 12:37

1 Answers1

1

If you only want to access that value inside onClick handler then you can bind that value with the action handler itself

const handler = (numbers, e) => {
    console.log(numbers)
}
render () {
    let numbers = { number:1, number2:2, number3:3 };
    return <div onClick={this.handler.bind(this, numbers)}>Test</div>;
}
Prakash Sharma
  • 15,542
  • 6
  • 30
  • 37
  • using .bind() or arrow function in the render method is not a good solution since it creates a new function everytime the render method is called. There are a lot of talks about avoiding this practice. Please check this question https://stackoverflow.com/questions/45053622/how-to-avoid-binding-inside-render-method/45053753#45053753 – Shubham Khatri Dec 30 '17 at 12:39