Home > front end >  React Suma of the numeric value from buttons
React Suma of the numeric value from buttons

Time:11-21

I could use a push in the right direction, I have total of 3 components named Shop, Shop2 and Shop 3, in each of the component I have a button that on press adds a 1 customer and has limit at 5, I have this 3 times (1 time in each component), how do I add an on screen count of how many customers are in (Suma of the numeric value from the amount of buttons pressed) fe. I pressed button A 3 times, button B 5 times and button C 2 times and I need to have displayed the suma, which would look like this: Total Customers: 10.

Here is the button component (I have this total of 3 times, components named Shop, Shop2 and Shop3)

render(props) {
    //@@viewOn:private
    const [count, setCount] = useState(0);

    function addCount() {
      setCount(prevCount => prevCount   1)
        }
    //@@viewOff:private

    //@@viewOn:interface
    //@@viewOff:interface
    //@@viewOn:render
    
    return (
      <div>
  <h1>Kaufland</h1>
  <p style={{ color: count > 4 ? "red" : undefined }}>Customers {count}</p>
  <Uu5Elements.Button
    
    onClick={count > 4 ? undefined : addCount}>
     1
  </Uu5Elements.Button>
</div>
    
    //@@viewOff:render
    )}

And I tried making it work in the final application that uses the components with this:

render(props) {
    //@@viewOn:private
      const [currentTime, setCurrentTime] = useState(new Date());
      const [count, setCount] = useState(0);
      useEffect(() => {
        setInterval(() => {
          setCurrentTime(new Date());
        },  1000);
      },
      []);
      
      function addCount() {
        setCount(prevCount => prevCount   1)
          }
      //@@viewOff:private

    //@@viewOn:interface
    //@@viewOff:interface

    //@@viewOn:render

return (
  <>
    <RouteBar />
  <div className={Css.mainContainer()}>
  <div>{currentTime.toLocaleString("cs")}</div>
      <h1>Total Customers {addCount}</h1>
      <Shop/>
      <Shop2/>
      <Shop3/>
  </div>
  </>
);

//@@viewOff:render
  }

Now when I press buttons, the value adds up only to each button as it should, but its not counting towards desired suma.

CodePudding user response:

Add your own const [count, setRootCount] = useState(0); to your root component and hand down setRootCount to your shop components. Then call both.

  • Related