Universally toggle between kilometers and miles with React/Redux

Viewed 104

Currently, I have a button that is toggling a ternary expression and it's working, but I can't imagine that creating a separate ternary expression for each line where I want to display data is the best practice.

Is there a better way to change between kilometers and miles across an entire page? My redux store contains both versions of the same distance and this is what I have so far:

const YourDistance = ({distanceInKms, distanceInMiles}) => {
const [isToggled, setToggled] = useState(false)

return (
    <div>
        { isToggled ? <h2>{distanceInKms}</h2> : <h2>{distanceInMiles}</h2> }
        <button onClick={() => setToggled(!isToggled)}>Convert</button>
    </div>
)};

If anyone has any ideas I would really appreciate it.

1 Answers

You can store the units in the redux state. That way you can have a selector function that returns the appropriate value based on both the distances in the state and the units in the state. You can just call const distance = useSelector(selectDistance) everywhere.

The selector might look something like:

const selectDistance = (state) => {
  const units = state.units;
  const {distanceInKms, distanceInMiles} = state.distance;
  return units === "miles" ? distanceInMiles : distanceInKms;
}

So we still have a ternary, but now it's just in one place instead of everywhere.

Obviously you would need to dispatch an action to toggle the units.

Related