简体   繁体   中英

How to make a child component of a sibling component refresh when a button is pressed in ReactJS?

So I have searched for solutions but I cant seem to find one that fits with what I am doing. Here is the structure of my website:

https://ibb.co/Xz27rgK

So as you can see I have my "NavBar" component outside of the Router because I always want it rendered. But I have a Dark mode toggle on the navbar, and when I click it I want it to update the refresh the Chart component (It is a react-chartjs-2 chart).

I know you can use setState(); to rerender, but how tell the Chart component to do that from the NavBar when I run the onClick(); function that I have inside of it?

For one component to trigger a re-render of a sibling component, or a child of a sibling, they must trigger a re-render of some shared parent component. In this case it would make sense for all components to be children of a single root component since the theme should be consistent across the entire project, unless you have some specific use case.

Probably the easiest way to do this is to pass in a callback setTheme as well as a theme attribute from the topmost component. In the setTheme callback, you should call the setState of that topmost parent component, which will then trigger a re-rendering of every child component with the new theme.

Take a look here for a more detailed description of how to change the theme of react components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM