V
V
Vladimir2020-02-16 00:56:48
JavaScript
Vladimir, 2020-02-16 00:56:48

How to replace a component when the window changes?

Goodnight. Can you please tell me how can I return the corresponding component when the window changes?

export default function TopBar() {

        return (
            <Router>

                <GetNavigationAndLogo />

            </Router>
        )

}

export const GetNavigationAndLogo = () => SelectNavigation(navigationItems);

const SelectNavigation = (menuItems) => {
    
    document.addEventListener('resize', () => {
        return window.innerWidth < 1000 && window.innerWidth > 700 ?
            getNavigationTablet(menuItems) :
            window.innerWidth < 700 ? getNavigationMobile(menuItems) :
                getNavigationPC(menuItems);
    });

    window.innerWidth < 1000 && window.innerWidth > 700 ?
        getNavigationTablet(menuItems) :
        window.innerWidth < 700 ? getNavigationMobile(menuItems) :
            getNavigationPC(menuItems);
    
};

Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2020-02-16
@HistoryART

You can update the application during resizing with this not tricky design:

window.onresize = () => {
    ReactDOM.render(<App />, document.getElementById('root'));
};

M
Max, 2020-02-16
@matios

Everything is simple. Add a state to SelectNavigation and store the flag of the desired type there:

state: {
  view: 'pc'; //pc | tablet | 'mobile'
}

Further, when resizing, you need to update this flag in the state, depending on the screen width.
And in the render function, output getNavigationTablet, getNavigationMobile or getNavigationPC depending on this.state.view.
In order for a component to re-render, you need to update its prop or state. In this case, if you update the state when resizing, the component will be redrawn when the state changes.
PS. Since you have a functional component, you can use the "useState" hook.
PS2. You have an error in the boundary conditions. Wrong condition for width = 700. In your case it will be PC? and should be tablet or mobile.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question