How do I change body background, depending on which component is showing on screen?

Viewed 29

I'm creating an e-commerce website using React Hooks and Router. Currently I have a blank home page, sign up and log in page. I want my background to change when the route changes to /signup. How do I add a background image when the Signup component loads? Below is my App component.

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route exact path ='/' element={<Home />} />
        <Route path='/signup' element={<Signup />} />
        <Route path='/login' element={<Login />} />
      </Routes>
    </BrowserRouter>
  );
}
1 Answers

You can add a current location check (using react router useLocation() method), and based on the desired value update css background:

import {Route, Link, Routes, useLocation} from 'react-router-dom';

const location = useLocation();

console.log('pathname', location.pathname);

Related