Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React recreates my component on each material ui tab switch

I added a Material UI Tabs component in my application, coding it almost similar to the one in their Simple Tabs demo.

I'm experiencing, though, that the components inside each tab — that is those at:

render() {
    /... 
    {
        value === 0 && < MyComponent1 / >
    } {
        value === 1 && < MyComponent2 / >
    } {
        value === 2 && < MyComponent3 / >
    }
    /...
}

are being recreated (I can trace this with a console.log() in their constructor) each time I switch tab losing their state, while I'd expect them to just be unmounted and remounted.

Am I doing something wrong or is that the normal behaviour?

like image 800
watery Avatar asked Jun 15 '18 08:06

watery


1 Answers

This is the expected behaviour for a component. Before it gets mounted, the constructor gets called. It might be worth giving the docs a re-read if you are unsure of the flow

https://reactjs.org/docs/react-component.html#constructor

If you want to components to keep state whilst it gets hidden/shown, you can pass through a flag (or className) which indicates whether to hide the component or not.

render() {
  /... 
  < MyComponent1 hidden={value === 0} / >
  < MyComponent2 hidden={value === 1} / >
  < MyComponent3 hidden={value === 2} / > 
  /...
}

The component can then use the prop to update what get's shown whilst still retaining state. e.g. you could add a class which hides it with css.

like image 156
Christopher Moore Avatar answered Oct 11 '22 20:10

Christopher Moore