'Reuse Child Component 'Instance' Across Multiple Parents
I am currently building a Dashboard using React and D3. I'd like to compose each Dashboard as their own component (rather than have a single mega component manage everything) but re-use the child components within each Dashboard which will allow smooth animations and transitioning.
The following is a very rough example of what I'm trying to achieve.
const Dashboard1 = () => {
const data = useData('/main');
return <ChartComponent data={data}/>;
};
const SubDashboard = () => {
const data = useData('/sub');
return <ChartComponent data={data}/>;
};
const App = (props) => {
return props.topLevel ? <TopDashboard/> : <SubDashboard/>;
};
The issue I am finding with this approach is that <ChartComponent>
will un-mount and re-mount when navigating between each Dashboard (due to the parents being different) which causing the page to flicker and all visuals to be redrawn which is expensive for some of the more complex visuals. What I would like to happen is for the same instance of <ChartComponent>
to be used on both dashboards between each render so that it doesn't unmount, gets the new data passed into it and can animate from the previous values to the new ones.
Are there are ways or patterns to achieve this?
Solution 1:[1]
You need a parent item that stores all the data and passes it down to child components but I'd suggest to do this with redux.
const Dashboard1 = (props) => {
return <ChartComponent data={props.data.main}/>;
};
const SubDashboard = (props) => {
return <ChartComponent data={props.data.sub}/>;
};
const App = (props) => (
// this should be load elsewhere, store in redux and use it here once loaded
const data = {
main: useData('/main')
sub: useData('/sub'),
};
return props.topLevel ? <TopDashboard data={data} /> : <SubDashboard data={data} />;
};
Solution 2:[2]
you need to use this react reparating npm module to do that. React doesn't provide support for it in-built. https://paol-imi.github.io/react-reparenting/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gary |
Solution 2 | Sai Deepthi |