Search code examples
reactjsattributesexportreact-props

Getting a state of from a component and show it as a value attribute inside a div?


In functional components
I want to share a function I have with a few components, to prevent duplicated code. All I need is the state that the function changes.

Is it possible to get the state from UpdateNum.jsx component to other components (as I showed in the code) ?
Or, is it possible to pass this function to other components so I can use it multiple times ? ( also to send props to the function)

    import { useEffect, useState } from 'react';
    
    export default function UpdateNum(change) {
      const [numberCon , setNumber ] = useState(0);
    
      useEffect(() => {    
          setNumber(numberCon + 1)
      },[change])

      return numberCon;

    }

I want to get the numberCon state in Shop.jsx inside the value={} attribute

import UpdateNum from './functions/UpdateNum';

  <div className='cart-icon' value={''}>
            <FaShoppingCart size={40} />
          </div>

And also at Items.jsx as I do -

import UpdateNum from './functions/UpdateNum';

 return (
    <div >
      <h1 style={{ marginLeft: '30px' }}>
         <UpdateNum/> - Items  <br />
      </h1>
    </div>
  );

Solution

  • UpdateNum function should return a component , if you want that function to return the actual state value , then you need to make it as a custom hook.

    1. prefix the function name with use so that react knows that it's a custom hook.
    import { useEffect, useState } from 'react';
    
    export default function useNumberCon() {
      const [numberCon , setNumber ] = useState(0);
    
        function riseNum() {   //Some function to calculate a number
          setNumber(numberCon + 1)
      }
    
      return { numberCon, riseNum};
    }
    
    1. Now in the component where you want to consume this numberCon and riseNum ( Shop.jsx and Items.jsx ) you can do this
    
    // In Shop.jsx
    const { numberCon, riseNum } = useNumberCon();
    
     ......
     ......
    
     <div className='cart-icon' value={numberCon}>
           <FaShoppingCart size={40} />
     </div>
    
    1. If your <Shop /> and the <Items /> are sibling to each other then you need to add the custom hook call ( step #2 ) in the parent component which wraps them .

    Reference:

    Custom Hooks

    Lifting State Up