Home > Mobile >  How to pass data(count) from Quantity component to Mainpart component using lifting state up in reac
How to pass data(count) from Quantity component to Mainpart component using lifting state up in reac

Time:11-16

Quantity component is my child class and Mainpart component is my parent class.i want to use my (count) in my parent class.but i dont know how to pass that data.sorry my english is not good.i think you will get the idea.

const MainPart = () => {

const submit = (event) => {
    debugger;
    event.preventDefault();

}

return (
    <div>
        <form onSubmit={submit}>
            <Container>
                <Row>
                    <Col sm={4}>
                        <Picture image='../images/test.jpg' alt='tent' />
                    </Col>
                    <Col sm={8}>
                        <Title title='4 Person tent' itemNo='Item No.  MA000001' />
                        <Currency mark='$' price='150.00' />
                        <Quantity />
                        <div style={{ marginTop: '5%', textAlign: 'center' }}>
                            <input type='submit' value='ADD TO CART' style={{ backgroundColor: 'yellow', padding: '5px 5px 5px 5px' }} />
                        </div>
                    </Col>
                </Row>
            </Container>
        </form>

    </div>
);

};


--------------------------------------------------------------------------------------------------

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

const increaseClick = () => {
    
    setCount(count   1 ) 
}

const decreaseClick = () => {
   
    setCount(count - 1 ) 
}

return (
    <>
        <div style={{ display: 'flex', marginTop: '5%', marginLeft: '30%' }}>
            <Button variant="primary" style={{ marginRight: '5%' }} onClick={decreaseClick}>-</Button>
            <h3>{count}</h3>
            <Button variant="primary" style={{ marginLeft: '5%' }} onClick={increaseClick}> </Button>
        </div>
        
    </>
);

};

CodePudding user response:

You have to create your state in parent and then pass to child, it will work.

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

   return (
     ...Your rest of code.
     <Quantity count={count} setCount={setCount} />
   )
}

Then In your child component, Use like this:

const Quantity = ({ count, setCount }) => {
  const increaseClick = () => {
    setCount(count   1 ) 
  }
  const decreaseClick = () => {
    setCount(count - 1 ) 
  }

return (
 <>
    <div style={{ display: 'flex', marginTop: '5%', marginLeft: '30%' 
  }}>
        <Button variant="primary" style={{ marginRight: '5%' }} onClick={decreaseClick}>-</Button>
        <h3>{count}</h3>
        <Button variant="primary" style={{ marginLeft: '5%' }} onClick={increaseClick}> </Button>
    </div>
    
  </>
);
}
  • Related