0

I want to create a function handleFalse() in react so it works something like:

state = {
  Java: false,
  Python: false
}

handleFalse(language) {
  this.setState({language}:true);
}

render() {
  return(
    <Modal onHide={this.handleFalse("show")}></Modal>
  )
}

where language would be one of Java or Python.

1 Answer 1

3

You can use a computed property like this:

handleTrue(language) {
  this.setState({ [language]: true });
}

You can reference an object property with a variable by using [].

This works when accessing too: this.state[language]

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but now I get an error saying "Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." Do you know why?
That's going to be unrelated to this code here, and most likely caused by where you are calling the function. Can you show how you are calling it?
Change to onHide={() => this.handleFalse("show")}. The way it is currently you are calling the handleFalse function every render, which sets state, which causes a re-render, and then repeats infinitely.
onHide={() => doSomething()} is assigning onHide a function. onHide={doSomething()} is assigning onHide the value of whatever doSomething returns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.