How to get key attribute of parent div when button is click in ReactJS
I want to get key attribute of parent div when child button is click. Using the code I write, I am getting null in console. Can't understand why?
I tried
let a = e.target.parentElement.getAttribute("key");
But this gives me null in console.
deletepost(e) {
let a = e.target.parentElement.getAttribute("key");
console.log(a);
}
render() {
return (
<div>
{ this.props.posts.map((post, i) =>
<div id="a" key="1">
<span> <h3>{post.title}</h3><p>{post.post}</p></span>
<input type="button" value="Delete" id="1" onClick={this.deletepost}/>
</div>
)
}
</div>
)
}
}
I am expecting "1" but getting null. Thanks in advance.
In ReactJS, the "key" is for React's internal use and won't be included in the DOM. That may be the reason you are getting null.
You need to simply add another prop/attribute. Something like below should work.
deletepost(e) {
let a = e.target.parentNode.getAttribute("postid"));
console.log(a);
}
render() {
return (
<div>
{
this.props.posts.map((post, i) =>
<div id="a" key="1" postId="1">
<span> <h3>{post.title}</h3><p>{post.post}</p></span>
<input type="button" value="Delete" id="1" onClick={this.deletepost}/>
</div>
)
}
</div>
)
}
}
Also, if the "id" on the input element is same as the "key" on your div (parent) element, then you can simply do the following:
deletepost(e) {
let a = e.target.id;
console.log(a);
}
render() {
return (
<div>
{
this.props.posts.map((post, i) =>
<div id="a" key="1">
<span> <h3>{post.title}</h3><p>{post.post}</p></span>
<input type="button" value="Delete" id="1" onClick={this.deletepost}/>
</div>
)
}
</div>
)
}
}
you can change 'key' attribute to 'data-key' and get attribute like this:
// Example class component
class Test extends React.Component {
constructor(props){
super(props);
this.deletepost = this.deletepost.bind(this);
}
deletepost(e) {
let a = e.currentTarget.parentNode.getAttribute("data-key");
console.log(a);
}
render() {
return (
<div>
{ this.props.posts.map((post, i) =>
<div id="a" data-key={post.key}>
<span> <h3>{post.title}</h3><p>{post.post}</p></span>
<input type="button" value="Delete" id={i} onClick={this.deletepost}/>
</div>
)
}
</div>
)
}
}
// Render it
ReactDOM.render(
<Test posts={[{post:'a',key:1},{post:'b',key:2}]} />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>
You can try with currentTarget
let a = e.currentTarget.parentNode.getAttribute("key");
Or
let a = ReactDOM.findDOMNode(this).parentNode.getAttribute("key")