Working with event listeners isn't as hard as I thought it would be in React. I will admit I had to still look up more information beyond the example, but it made sense once you utilized it. Let's logically think about how we would change content in the view based on the size of the screen. Well, we would get the window size and then use an if or switch to set the desired view. Now all that is left is to call the function when the resize event occurred. In React, a first draft would look like this:
import { useState, useEffect } from "react";
const AutoResize = () => {
const [state, setState] = useState(window.innerWidth);
useEffect(() => {
setState(
window.innerWidth);
},[]);
if (state < 500) {
return < ViewOne />
}
return <ViewTwo />
};
When this script begins, the states is equal to the current width of the window. Then if state's value is less than 500px it will use ViewOne and if it's larger, it will use ViewTwo. While this works, there is a flaw. This script will only check the window width on first run or on a refresh. So if you're on a mobile device and the screen rotates, the view will remain the same. Resizing does not reload the page. Hence, we need to add an event trigger that will execute when the window is resized. Also, we want to ensure that once the trigger has done its job that it's unloaded from memory. So the solution is:
import { useState, useEffect } from "react";
const AutoResize = () => {
const [state, setState] = useState(window.innerWidth);
useEffect(() => {
window.addEventListener('resize', ()=>setState(
window.innerWidth));
return ()=>
window.removeEventListener('resize', ()=>setState(
window.innerWidth));
},[]);
if (state < 500) {
return < ViewOne />
}
return <ViewTwo />
};
Notice that the useEffect returns the removal of the event. So when the component is not in use, it will remove the event listener from memory. All in all a nice addition to the ongoing website.