I know there are a lot of answers to this situation which involves using bind or arrow function but my situation is a bit different. Basically I want to create a div element with an EventListener that updates the state setIndex value with the index value of the specific child element that I clicked.The callback function for this process is the onModal
If I use arrow function for the onModal, the 'this' keyword gets transferred to the class instead of the individual elements and hence I wont be able to access the index for the individual elements.
If I using the normal function(as I have demonstrated in the code below), the this.setState gets transferred to the individual elements and I get the setState error
class AddRecipe extends Component{
constructor() {
super();
this.state={
name:[],
setIndex:0,
}
}
onLoad() {
var recipe = document.querySelector(".recipe")
const name = data.forEach((d,index) => {
var recipecard = document.createElement("div")
recipecard.setAttribute("class","recipecard")
recipecard.setAttribute("key",index)
recipe.setAttribute("key",0)
var h1 = document.createElement("h1")
h1.setAttribute("id","keyhold")
h1.appendChild(document.createTextNode(data[index].name))
console.log(h1);
recipecard.appendChild(h1)
recipecard.addEventListener("click",this.onModal)
recipe.appendChild(recipecard)
})
}
componentDidMount() {
this.onLoad()
}
onModal() {
var index = this.getAttribute("key")
var recipe = document.querySelector(".recipe")
recipe.setAttribute("key",index)
var modal = document.getElementById('MyModal')
var btn = document.getElementById('myBtn')
var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
modal.style.display = "block";
this.setState({setIndex:index}).bind(this)
}
onClose() {
var modal = document.getElementById('myModal');
var span = document.getElementsByClassName("close")[0]
modal.style.display= "none"
}
render() {
return (
<div>
<div id="myModal" class="modal">
<div class="modal-content">
<span onClick={this.onClose.bind(this)} class="close">×</span>
<ModalWindow datas= {data} index={this.state.setIndex} />
</div>
</div>
<div className ="recipe">
</div>
</div>
);
}
}
export default AddRecipe
bind
method onsetState
and also, probably the error is in the linerecipecard.addEventListener("click",this.onModal)
you need to add a bind to thethis.onModal
call.