1

I'm trying to loopover an array to render items in a list (in react native). Every item has a button. How can I change the background color of this specific button, when someone clicks it? I already tried .setState but the problem is, that it changes the background color of every button in the list.

 this.setState({btnColor: 'red' }); 

What can I do? Is there a way to create new states dynamically?

Thank you.

0

1 Answer 1

1

You can take such approach:

 class App extends React.Component {
  state = {
    colors: {},
    btnIds: [1, 2, 3]
  };

  render() {
    return (
      <div>
        {this.state.btnIds.map(x => (
          <button
            onClick={() => {
              this.setState(ps => ({
                colors: {
                  ...ps.colors,
                  [x]: "red"
                }
              }));
            }}
            style={{ backgroundColor: this.state.colors[x] || "" }}
          >
            {x}
          </button>
        ))}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.9/angular.min.js"></script>
<div id="root"/>

react demo though IMHO same should apply on RN.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.