M
M
Michael R.2020-08-17 15:28:47
React
Michael R., 2020-08-17 15:28:47

How to handle click on each Counter in each child component?

Greetings!

You need to create a counter and listen for it to change in each individual child component (counter is an example https://reactjsexample.com/react-counter/ ).

Ready counter is not interested, because I want to understand exactly the algorithm for solving the current problem ...

For clarity, I sketched a simple example:

function Parent() {
  function dec() { console.log("decrement"); }
  function inc() { console.log("increment"); }
  
  return(
    <div className="childs">
      {[1, 2, 3].map((data, i) => {
        return <Child key={i} dec={dec} inc={inc} />
      })}
    </div>
  );
}

function Child(props) {
  return(
    <div className="child">
      <div className="child__decrement">-</div>
      <input type="number" className="child__input" defaultValue="0"/>
      <div className="child__increment">+</div>
    </div>
  );
}


When clicking on .child__decrementit is necessary to increase the value of .child__input, and to decrease when clicking on .child__increment. Please note that there will be several such child components.

How to competently solve such a problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-08-17
@Mike_Ro

Store count values ​​separately in each instance of Child .
Or all together in Parent , and pass them to Child along with a function that will set the new value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question