Looking to enhance my simple app with a few pages by changing the background color based on page URL using React.js.
What I aim to achieve:
If the pathname is /movies
, I want the background color to be red.
This is my current progress:
import React, { useState } from 'react';
function Testing() {
const [moviesUrlBackgroundColor, setMoviesUrlBackgroundColor] = useState('green');
const getMoviesUrl = window.location.pathname;
if (getMoviesUrl === '/movies') {
setMoviesUrlBackgroundColor('red');
} else {
setMoviesUrlBackgroundColor('green');
}
return (
<div>
<Container style={{backgroundColor: moviesUrlBackgroundColor}}>
Testing
</Container>
</div>
);
}
export default Testing;
const Container = styled.div`
background-color: green;
`;
However, I am encountering the following issue:
app.js:38323 Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop.
How can I resolve this problem and make it work as intended?