Reputation: 145
I have a React "tree" menu component which has main links with submenus which are dynamically generated by a JSON get call. In the React Inspector I can see that each element on the tree has several props but when I click on each element the only one I can access is value. Here is the props list:
{
"checked": 0,
"className": null,
"label": "192.168.1.71",
"isLeaf": false,
"isParent": true,
"title": null,
"treeId": "rct-~xDYGzs",
"value": "5bd350bf-8515-4dc2-9b12-16b221505593",
}
Here is the code for accessing the value (which was provided in the component API):
onClick(clicked) {
this.setState({ clicked });
console.log('You clicked on ' + clicked.value);
}
If I substitute any other prop name (like "treeId") for clicked.value I get "undefined". I've tried every variation of e.target and getAttributes but nothing is working. Hopefully this is enough info to get some advice but I can definitely add more if needed. Thanks in advance.
Addendum: This is all being scripted into a pre-existing component called react-checkbox-tree so putting together a Codesandbox would be kind of difficult. I did a console.log(clicked) as suggested and got the following:
{value: "5bd81d67-3fd5-464a-b115-161ce291c2d8", checked: false}
For whatever reason the remaining props besides value and checked are not reporting and I can't access them and I have tried everything imaginable.
Upvotes: 0
Views: 577
Reputation: 3652
The reason you can only get the [value] prop from your onClick is because other data doesn't get passed along in a mouse event. If you want to return all of the props from your subcomponent you can adjust the way you're writing your click handler to return a function like this:
class MainComponent extends Component {
handleClick(props) {
console.log(props); /* whatever you sent from the sub component */
}
render() {
return (
<SubComponent
subComponentClicked={this.handleClick}
/>
);
}
}
class SubComponent extends Component {
handleClick = () => {
this.props.subComponentClicked(this.props);
}
render() {
return (
<div onClick={this.handleClick}></div>
);
}
}
Upvotes: 0
Reputation: 22911
this.setState({ clicked })
is shorthand for this.setState({ clicked: clicked })
. This is called Object Destructuring. If you change that to anything else, then it will rewrite it to (In the case of treeId): treeId: treeId
(The variable being passed in to the onClick
function is named clicked
, so treeId
will be undefined.)
If you want to set treeId
to clicked.value
, simply use:
this.setState({
treeId: clicked.value
});
You can still use the object destructing in the parameter, if value
is on the clicked
object, and that's all you care about:
onClick({ value }) {
this.setState({ treeId: value });
console.log(`You clicked on ${value}`);
}
Upvotes: 1