0

in my application I use generic Tabs functional component:

export default function Tabs() {
    const [currentTabIndex, setCurrentTabIndex] = useState(0);

    [...]
}

Now in my BookingPage I need to change the currentTabIndex of this Tabs component, depending on Redux Store:

export default function BookingPage()
    const userCreatedBooking = useSelector([...]); // whenever this value change, I want
                                                   // to invoke Tabs.setCurrentIndex 

    return (
     <>
         <Tabs tabs=[SubPage1, SubPage2]/>
     <>

What's a clean way to achieve above? Thanks;)

Rob D
  • 71
  • 1
  • 6

1 Answers1

1

A clean way is to connect your component to redux and the redux value will be in the props of the component.

If you want to use setCurrentTabIndex every time a value in redux is changed you can use useEffect

An example of useEffect is in the answer of this post post

Edit

I can give you an exemple.

import React, {useState, useEffect} from 'react'

export default function Tabs(props) {
    const [currentTabIndex, setCurrentTabIndex] = useState(0);
    
    useEffect(() => {
      // Runs ONCE after initial rendering
      setCurrentTabIndex(props.value)
    }, [props.value]); // Will only run if props.value change
    [...]
}

export default function BookingPage() {
    const userCreatedBooking = useSelector([...]);

    return (
     <>
         <Tabs 
         value={userCreatedBooking} // or any value in your redux
         tabs=[SubPage1, SubPage2]
         />
     <>
     )
}

More information on useEffect and how to connect your component to redux

docmurloc
  • 1,201
  • 4
  • 11
  • Hi, could you elaborate on this solution? I still don't see, how would I invoke `Tabs.setCurrentIndex ` from the `BookingPage` component. – Rob D Mar 24 '21 at 09:37
  • I give you an example in the answer – docmurloc Mar 24 '21 at 17:15
  • docmurloc, your answer works great – but perhaps I have not emphasized enough that this is a generic component which I cannot modify (plenty of other people in the company use it). Is there a way to achieve what you have suggested without changing the code within `Tabs` component? – Rob D Mar 24 '21 at 17:59
  • There is no way to achieve this without changing something in the Tabs component. The child component needs to be aware of a change to have a side effect. You can only use props, hooks or reference in your child component by changing your code in Tabs. – docmurloc Mar 24 '21 at 18:44
  • Ok, thanks for explanation:) I'm marking your answer as accepted. – Rob D Mar 24 '21 at 20:40