React, make state apply to single element in loop

react for loop array
react conditional render multiple elements
react map
react state
react loop through array of objects
react foreach
react loop through object
each child in a list should have a unique "key" prop.

I have 3 circles that should change src of image when toggled, currently all circles toggle the src when one is clicked. I could use some help with how to get that problem fixed.

This is what i got right now

this.state = {
      fillCircle: false
    };

  circleHandler = () => {
    this.setState({ fillCircle: !this.state.fillCircle });
  };
 
 render() {
    let circles = [];
    for (var i = 0; i < 3; i++) {
      circles.push(
        <img
          key={i}
          className="circle"
          onClick={this.circleHandler.bind()}
          src={this.state.fillCircle ? filled_circle : circle}
          alt=""
        />
      );
    }
    return (
        <div>
         {circles}
        </div>
    );

This is because each of those elements needs it's own state. Write a separate component for each circle. Then you would do

circles.push(<CircleComponent key={index} />)

Inside CircleComponent you would have your state for each Component and toggle for each one of them. Don't forget about keys as well.

Conditional Rendering – React, In React, you can create distinct components that encapsulate behavior you you can render only some of them, depending on the state of your application. like if or the conditional operator to create elements representing the current state​,  State Updates May Be Asynchronous. React may batch multiple setState () calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. manipulate state with a functional approach.


Didn't try it, but you should get the concept.

this.state = {
    fillCircle: [false,false,false]
};

  circleHandler = (i) => {
        this.setState((prev) => {
            if(prev.fillCircle[i] == false)prev.fillCircle = [false,false,false] // <--
            prev.fillCircle[i] = !prev.fillCircle[i];
            return prev.fillCircle;
        });
  };

 render() {
    let circles = [];
    for (var i = 0; i < 3; i++) {
      circles.push(
        <img
          key={i}
          className="circle"
          onClick={()=> this.circleHandler(i) }
          src={this.state.fillCircle[i] ? filled_circle : circle}
          alt=""
        />
      );
    }
    return (
        <div>
         {circles}
        </div>
    );

How to For Loop in React (With Examples), Although we can write a for loop in React, ES6 provides the more We can add state to functional components, therefore I like to always use functional Our functional React component returns a single div element with some JSX inside. a set of <li> tags for each element in the array, thus creating a list:. Using Array map function is very common way to loop through an Array of elements and create components according them in React, this is a great way to do a loop which is pretty efficient and tidy way to do your loops in JSX, It's not the only way to do it, but the preferred way. Also, don't forget having a unique Key for each iteration as required.


@Dille Please try below code this should solve your problem.

this.state = {
          activeCircle: null
        };

      circleHandler = (i) => {
        this.setState({ activeCircle: i});
      };

     render() {
        let circles = [];
        for (var i = 0; i < 3; i++) {
          circles.push(
            <img
              key={i}
              className="circle"
              onClick={this.circleHandler.bind(this, i)}
              src={this.state.activeCircle === i ? filled_circle : circle}
              alt=""
            />
          );
        }
        return (
            <div>
             {circles}
            </div>
        );

React Design Patterns and Best Practices: Design, build and deploy , Design, build and deploy production-ready web applications using standard The function used to validate the condition receives the props, state, and Loops​. A very common operation in UI development is to display lists of items. JSX has been built in such a way that it only abstracts the creation of the elements,  In React, this element can have a state. And anytime the state changes, a new React element is created. React compares these elements and figures out what has changed. Then, it reaches out to the real DOM and updates only the changed object. Let’s render the React element inside of the real DOM for us to see.


How to Work with and Manipulate State in React, The state object is an attribute of a component and can be accessed with this can import and use in their application without having to jump through hoops. We can't setState in render() either, because it'll create a circular (setState >​render >setState…) loop and, in this case, React will throw an error. To set the initial state, use this.state in the constructor with your ES6 class React.Component syntax. Don’t forget to invoke super() with properties, otherwise the logic in parent ( React


How to loop inside React JSX, If you have a set of elements you need to loop upon to generate a JSX partial, you can create a loop, and then add JSX to an array:. Learn how to loop & output from arrays of data in React. Help spread the word about this tutorial! Iterating and displaying data is a very common part of building applications. In React (and other frameworks), the most basic way of doing this is hard coding the entries into your HTML ( view code ): But what if our names were in an array, and


React Design Patterns and Best Practices, Loops. A very common operation in UI development is to display lists of items. Suppose you have a list of users, each one with a name property attached to it. To create an unordered list to show the users, you can do the following: <ul> we have to show and hide elements according to the state of the application, and​  We will later update this state. React then calls the Clock component’s render() method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the Clock’s render output. When the Clock output is inserted in the DOM, React calls the componentDidMount() lifecycle method.