1

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">&times;</span>
            <ModalWindow datas= {data} index={this.state.setIndex} />
          </div>
        </div>
        <div className ="recipe">
        </div>
      </div>
    );
  }
}

export default AddRecipe
5
  • remove .bind(this) after this.setState Jun 28, 2018 at 14:56
  • 2
    I think there's no need to use the bind method on setState and also, probably the error is in the line recipecard.addEventListener("click",this.onModal) you need to add a bind to the this.onModal call. Jun 28, 2018 at 14:57
  • 1
    You could have the errors highlighted by other user, but the real error is that React is not build to work with document (document.createElement) and other similar things. You have to use the render and the state to understand what render. You can use the React ref API to get elements infos. Jun 28, 2018 at 14:59
  • It looks to me like your onLoad() is doing a lot of juggling to avoid using refs, but refs have gotten a lot easier to use in React 16. If I were doing this I would create a RecipeCard class and attach my event handler to that using refs. Here's the documentation (reactjs.org/docs/refs-and-the-dom.html), let me know if you want more info on implementing this. Jun 28, 2018 at 15:02
  • 1
    I'm 100% with @PaoloDell'Aguzzo, is better to create another component with all the information that you need instead of manipulating the DOM directly Jun 28, 2018 at 15:03

4 Answers 4

1

Pass the index argument over to the event handler and process accordingly.

Also, since you wanted the element context only for retrieving the index, you can send the index along to the onModal method by using function currying. This way you need not depend on the element's context anymore.

If your React project supports arrow functions for class instance methods then you can try passing the arguments like below.

class AddRecipe extends Component{
  ...
  onLoad() {
    var recipe = document.querySelector(".recipe")
    const name = data.forEach((d,index) => {
      ...
      recipecard.addEventListener("click",this.onModal(index))             
      recipe.appendChild(recipecard)
    })
  }

  onModal = (index) => (event) => {
    ...    
    this.setState({ setIndex:index })    
  }
  ...
}

export default AddRecipe

OR

You can even try the way it's documented in the React Docs to avoid any confusion https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers

class AddRecipe extends Component{
  ...        
  onLoad() {    
    var recipe = document.querySelector(".recipe")    
    const name = data.forEach((d,index) => {
      ...
      recipecard.addEventListener("click",(event) => this.onModal(index))             
      recipe.appendChild(recipecard)
    })
  }

  onModal = (index) => {
    ...    
    this.setState({ setIndex:index })    
  }
  ...
}

export default AddRecipe

Check out this article to see the many ways of sending parameters to event handlers

https://medium.freecodecamp.org/reactjs-pass-parameters-to-event-handlers-ca1f5c422b9

1
  • i have never seen events handled that way but your method gave the best answer..thanks Jun 28, 2018 at 16:10
1

Probably the error is in the line recipecard.addEventListener("click",this.onModal) you need to add a bind to the this.onModal call.

I think there's no need to use the bind method on setState.

1
  • The bind to the setState was a typo. Does binding the onModal make it refer to the AddRecipe class instead of the recipe card though? Jun 28, 2018 at 16:13
1

bind will attach the first argument as the context (i.e. 'this") of the function you are calling bind on and return a new function with the new context.

this.setState({...}) is a function call, thus it is not possible to bind any this. you need something like this:

onLoad(){

  var recipe = document.querySelector(".recipe")
  const name = data.forEach((d,index) => {
    (...)
    // !!! bind this to onModal
    recipecard.addEventListener("click",this.onModal.bind(this))
    (...)
}) }

so if you bind 'this' to onModal, the function called on the click event will use the context of your class and therefore it can call setState of your class.

edit

you can use the second part of Nandu Kalidindis answer, too. arrow functions automatically have the context of the place where they are created therefore the context of onLoad which is the context of the class.

0

recipecard.addEventListener("click",this.onModal.bind(this)) onModal have to be bind and I'm not sure if this will be working without binding

 componentDidMount() {
    this.onLoad()
 }

in constructor add line of code

this.onLoad = this.onLoad.bind(this)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.