reactjsreact-reduxstatetoggle

React using toggle switch to change state of sibling components


I'm working on an app where I want to change a value from lbs to kgs. I currently have the state set to lbs and am trying to add a toggle switch which will allow users to toggle between lbs and kgs. I'm having trouble passing the state between sibling components.

Here is my code:

const HomePage = (props) => {
    const {
        movements
    } = props;

    const convertToKg = (_id) => {
        const kg = movements.map((movement) => {
            return {_id: movement._id, movementName: movement.movementName, movementWeight: movement.movementWeight * 0.453592}   
        })
        return kg;
    } 

   return (
       <div>
            <div>
                <MovementButtons movements={movements} />
            </div>
            <div>
                <WeightConverter onClick={convertToKg} />
            </div> 
       </div>
   );
};

export default HomePage;

and my toggle switch code:

const WeightConverter = (props) => {
    const {
        onClick
    } = props;
    
    return (
        <div>
            lb
            <Switch 
                onClick={onClick}
                >  
            </Switch>
            kg
        </div>   
    )
};

I'm not even sure I'm using the toggle switch correctly.

Basically what I want is for the 'movements' state to change to the result of convertToKg when the toggle switch is activated, and then back to it's original state when it is toggled back. If I need to show more code or answer any questions please ask. I just need a nudge in the right direction.


Solution

  • You are kinda in right direction but this are the mistakes you are making:

    1. Your function convertToKg will be converting everyweight to kg but there is no toggle logic here, you cant go back to lbs from this function.
    2. For toggle you need to maintain a state whether currently you need to switch to kg or lbs
    3. Your function is working properly convertToKg but the thing is react doesnt know it, you are not passing the object back to MovementButtons; make use of useState for this

    I want you to explore this:

    1. Make use of state logic in react to track unit (kg or lbs)
    2. And instead of changing the whole object; pass this unit to your MovementButtons component and then apply the logic of conversion to that particular unit, this way you have your original data

    I hope this helps, I am not giving you a code directly since you are asking to be pushed in right direct but do reply if you need a little extra help.