0

I have an array of items which individually has a button, I want to disable the button of an item when I click on the Item. I have tried creating an array of disabled items in the state and setState onClick of the Button but I keep getting errors. Here is my Component code below.

class MovieSummary extends Component {
  constructor(props) {
    super(props);

    this.state = {
   
      disabled: [],
    };
  }

  addingItem = (item) => {
    this.props.addItem(item);
  };

  render() {
    const { Title, imdbID } = this.props.movie;
    return (
      <div>
        {" "}
        <h5>
          {this.props.movie.Title}{" "}
          <button
            key={imdbID}
            disabled={this.state.disabled.indexOf(imdbID) !== -1}
            onClick={
              (() =>
                this.addingItem({
                  title: Title,
                  id: imdbID,
                }),
              this.setState({
                disabled: [...this.state.disabled, imdbID],
              }))
            }
          >
            Nominate
          </button>
        </h5>
      </div>
    );
  }
}

export default MovieSummary;
2
  • why not when you call this.props.addItem to also set a disabled flag on your movie object? Commented Sep 13, 2020 at 4:08
  • In the onClick function, you can simply write two statements: onClick = { () => this.addingItem({...}); this.setState({ ... }) } You know what to fill in place of '...' Commented Sep 13, 2020 at 4:13

1 Answer 1

1

Wherever you're mapping through movies, you could simply check whether the movie exists in the added movies list or not and disable the button accordingly.

class ComponentThatWrapsMovieSummary extends Component {
  state = {
    addedMovies: [],
  }
  
  render() {
    return (
      {movies.map(movie => {
        // wherever you're mapping, you could simply check like this.
        return <MovieSummary isDisabled={this.addedMovies.includes(movie.id)}/>
      })}
    )
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.