简体   繁体   中英

change text of a specific button when clicked in React

I want to change the text of a specific button when I click on that button in React. But the issue is when I click the button the title will change for all buttons!

class Results extends Component {

    constructor() {
        super();
        this.state = {
            title: "Add to watchlist"
        }
    }

    changeTitle = () => {
        this.setState({ title: "Added" });
    };
    
    render() {
        return (
            <div className='results'>
                {
                    this.props.movies.map((movie, index) => {
                        return (
                            <div className='card wrapper' key={index}>
                                <button className='watchListButton' onClick={this.changeTitle}>{this.state.title}</button>
                            </div>
                        )
                    })
                }
            </div>
        )
    }
}

You would need to come up with a mechanism to track added/removed titles per movie. For that, you would have to set your state properly. Example:

this.state = {
      movies: [
        {id: 1, title: 'Casino', added: false},
        {id: 2, title: 'Goodfellas', added: false}
      ]

This way you can track what's added and what's not by passing the movie id to the function that marks movies as Added/Removed. I have put together this basic Sandbox for you to get you going in the right direction: https://codesandbox.io/s/keen-moon-9dct9?file=/src/App.js

And here is the code for future reference:

import React, { Component } from "react";
import "./styles.css";

class App extends Component {
  constructor() {
    super();
    this.state = {
      movies: [
        { id: 1, title: "Casino", added: false },
        { id: 2, title: "Goodfellas", added: false }
      ]
    };
  }

  changeTitle = (id) => {
    this.setState(
      this.state.movies.map((item) => {
        if (item.id === id) item.added = !item.added;

        return item;
      })
    );
  };

  render() {
    const { movies } = this.state;
    return (
      <div className="results">
        {movies.map((movie, index) => {
          return (
            <div className="card wrapper" key={index}>
              {movie.title}
              <button
                className="watchListButton"
                onClick={() => this.changeTitle(movie.id)}
              >
                {movie.added ? "Remove" : "Add"}
              </button>
            </div>
          );
        })}
      </div>
    );
  }
}

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM