2

I have a React Project!

Project contains 4 components

Home, About, Login, Alert

So Alert.js will show on every page. I want Alert.js will show only on the Home component. Not on any other component. How can I do that? There are other similar questions. I have tried all. I didn't get any results.

This is my App.js

import React, { Component } from 'react'
import Nav from './COMPONENT/navbar/Nav'
import { Route } from 'react-router';
import Home from './COMPONENT/navbar/Home';
import Login from './COMPONENT/navbar/Login';
import About from './COMPONENT/navbar/About';
import Alert from './COMPONENT/navbar/Alert';

export class App extends Component {
  render() {
    return (
      <>
        <Alert/>
        <Nav />
  
            <Route exact path="/">
              <Home />
            </Route>

            <Route exact path="/about">
              <About />
            </Route>

            <Route exact path="/login">
              <Login />
            </Route>
      </>
    )
  }
}

export default App
Abhijeet Abnave
  • 801
  • 6
  • 16

3 Answers3

0

Try this

    return (
      <>
        <Nav />
  
            <Route exact path="/">
              <Alert/>
              <Home />
            </Route>

            <Route exact path="/about">
              <About />
            </Route>

            <Route exact path="/login">
              <Login />
            </Route>
      </>
    )
  }```
0

You can use the useLocation hook from react-router and conditionally render the alert.

import {use-location} from react-router

const {pathname} = useLocation();

  <>
    {pathname === "/" && <Alert/>}
    <Nav />

        <Route exact path="/">
          <Home />
        </Route>

        <Route exact path="/about">
          <About />
        </Route>

        <Route exact path="/login">
          <Login />
        </Route>
  </>
)

} }

Farrukh Rashid
  • 185
  • 1
  • 9
0

You can use window.location.pathname to check current location. Check pathname equals to '/'

Your Alert.js should like this.

const Alert = () => {
  const location = window.location.pathname;
  if (location === '/') return <div>Alert</div>;
  else return <div />;
};
Rahul
  • 405
  • 1
  • 4
  • 15