1

counterScreen.js

import React, { useState } from "react";

const CounterScreen = () => {
    const [count, setCount] = useState(0);

    return (
        <div>
            <h2>This the number: {count}</h2>
        </div>
    ) }

export default CounterScreen

addButton.js

import React from 'react'

const AddButton = () => {
    return (
        <div>
            <button>+</button>
        </div>
    ) }

export default AddButton

subtractButton.js

import React from 'react'

const SubtractButton = () => {
    return (
       <div>
            <button>-</button>
        </div>
    ) }

export default SubtractButton

i want when i click the button in addbutton.js the counter should add 1 and when i click the button in subtractbutton.js the counter should subtract 1

what will be the best way to share the state here please help

edemaine
  • 2,699
  • 11
  • 20
naveed
  • 111
  • 8

1 Answers1

1

One simple way to solve this is to put the state in the containing component, and pass in values or callbacks to the relevant components:

const Counter = () => {
    const [count, setCount] = useState(0);
    return (
        <div>
            <CounterScreen count={count}/>
            <AddButton onClick={() => setCount(count+1)}/>
            <SubtractButton onClick={() => setCount(count-1)}/>
        </div>
    );
};

const CounterScreen = ({count}) => {
    return (
        <div>
            <h2>This the number: {count}</h2>
        </div>
    )
};

const AddButton = ({onClick}) => {
    return (
        <div>
            <button onClick={onClick}>+</button>
        </div>
    )
};

const SubtractButton = ({onClick}) => {
    return (
        <div>
            <button onClick={onClick}>-</button>
        </div>
    )
};
edemaine
  • 2,699
  • 11
  • 20
  • after this do is pass only coounter as a component in index.js since it contains other components?? – naveed Jul 05 '21 at 15:49
  • You can split all four of these components into separate files if you'd like, depending on how you want to re-use them; I was just showing the functional code and not `import`/`export` etc. – edemaine Jul 05 '21 at 15:54
  • it actually worked for me thanks again i am getting a bit better understanding now thanks again – naveed Jul 05 '21 at 16:26