1

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> ); 

} }

2 Answers 2

2

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); } } 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.