naveed
naveed

Reputation: 111

i want to increment and decrement the number when the button from other component is clicked

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

Upvotes: 1

Views: 509

Answers (1)

edemaine
edemaine

Reputation: 3130

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>
    )
};

Upvotes: 1

Related Questions