Alvin
Alvin

Reputation: 11

React multiple button on page, to know which one clicked

I have multiple buttons on my screen and and inside same container I have another label, on click I want to show the label and then hide after few seconds.

I am controlling through this.state problem is when event fires it shows all labels and then hides all. I found few solutions like assign ids etc and array for buttons.

But issue is there can be unlimited buttons so thats not the way to go to set state for each button. Or if there is any other possible way.

export default class App extends React.Component {
constructor(props) {
    super();

    this.state = {
        visible: false
    }
}

_handleClick = () => {
    this.setState({
        visible: !this.state.visible
    });
    setTimeout(() => {
        this.setState({
            visible: false
        });
    },2000);
}
  render() {
return (


    <div>
        <button onClick={this._handleClick}>Button 1</Text></button>
        {this.state.visible && <span style={styles.pic}>
                Pic
            </span>
        }
    </div>

    <div>
        <button onClick={this._handleClick}>Button 2</Text></button>
        {this.state.visible && <span style={styles.pic}>
                Pic
            </span>
        }
    </div>


    <div>
        <button onClick={this._handleClick}>Button 3</Text></button>
        {this.state.visible && <span style={styles.pic}>
                Pic
            </span>
        }
    </div>

  </div>
);

} }

Upvotes: 1

Views: 4857

Answers (2)

Xander
Xander

Reputation: 1726

You need each button to have its own state... So make each button a Component!

class App extends React.Component {

    render() {
        return <div>
            <Button>1</Button>
            <Button>2</Button>
            <Button>3</Button>
            <Button>4</Button>
        </div>
    }

}

class Button extends React.Component {

    constructor(props) {
        super();

        this.state = {
            visible: false
        }
    }

    _handleClick = () => {
        this.setState({
            visible: !this.state.visible
        });
        setTimeout(() => {
            this.setState({
                visible: false
            });
        }, 2000);
    }
}

Upvotes: 2

nine9stars
nine9stars

Reputation: 247

If there are unlimited buttons, then you can set the state like this regarding which button is clicked.

_handleClick = (id) => {
  this.setState({ [id]: true })
}

id will be the unique id of each button. Here is a simple example to show how to set the state. https://codesandbox.io/s/k38qyv28r

Upvotes: 0

Related Questions