Answer the question
In order to leave comments, you need to log in
Reactjs Context API how to change state when user's screen size changes?
Good afternoon! Help, please, to understand. The task is to change the Context state when changing the user's screen size. The application of specific styles of the entire application depends on this state. There is a division into mobile and PC version. The isMobile state is responsible for this option. It is necessary to manipulate it specifically and when the browser size changes, cause it to change. I don't know when exactly to do it.
The state is stored here:
class ProductProvider extends Component {
state = {
isMobile: false,
sidebarOpen: false,
loading: true
handleIsMobileMode = () => {
this.setState({ isMobile: !this.state.isMobile });
};
handleSidebar = () => {
this.setState({ sidebarOpen: !this.state.sidebarOpen });
};
closeSideBar = () => {
this.setState({ sidebarOpen: false });
};
render() {
return (
value={{
...this.state,
handleSidebar: this.handleSidebar,
closeSideBar: this.closeSideBar,
handleIsMobileMode: this.handleIsMobileMode
}}
>
{this.props.children}
);
}
}
The isMobile state change trigger from falase to true must be called here: const App = ({ width }) => {
const location = useLocation();
const routesArray = [];
menuData.forEach(item => {
item.items.forEach((element, index) => {
routesArray.push(
path={`/${element.slug}`}
key={index}
exact
component={() => }
/>
);
});
});
if (width > 756) {
return (
{routesArray}
);
} else {
return (
{value => {
const { isMobile, handleIsMobileMode } = value;
return (
);
}}
);
}
};
Answer the question
In order to leave comments, you need to log in
import React from 'react';
class ShowWindowDimensions extends React.Component {
state = { width: 0, height: 0 };
render() {
return <span>Window size: {this.state.width} x {this.state.height}</span>;
}
updateDimensions = () => {
this.setState({ width: window.innerWidth, height: window.innerHeight });
};
componentDidMount() {
window.addEventListener('resize', this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question