Randy
Randy

Reputation: 1287

How can I tell in the `LogoHeader` component, what route I am in

I have two routes defined in my App.js file:

        <BrowserRouter>
            <p className="greeting">Hello, {token.firstName}</p>
            <LogoHeader />
            <GetCategories />
            <Navbar id="customNav" navItems={navItems} shopCategories={shopCategories} />
            <Switch>
                <Route path="/portal">
                    <Portal />
                </Route>
                <Route path="/">
                    <Slideshow id="slideshow" />
                    <div id="productContainer">
                        <br />
                        <h3>Featured Products</h3>
                        <br />
                        <FeaturedCards />
                        <br />
                        <h3>Most Popular</h3>
                        <br />
                        <ProdCard />
                        <br />
                        <h3>New Products</h3>
                        <br />
                        <ProdCard />
                    </div>
                </Route>                               
            </Switch>
            <NewFooter />
        </BrowserRouter>

In my LogoHeader component I have a <NavLink><svg/></NavLink> that points to /portal. I wanna switch the svg and link to / (Home) if I am in portal. I thought about reading window.location.pathname but it shows '/' no matter what route I am in. How can I tell in the LogoHeader component, what route I am in?

UPDATE

I am showing my LogoHeader with what I think @YogeshYadav is talking about in his answer:

import React from 'react';
import { NavLink } from 'react-router-dom';
import Config from 'config';
import { Helmet } from "react-helmet";
import { Jumbotron, Container } from 'reactstrap';

class LogoHeader extends React.Component {
    constructor({ history }) {
        super();
        this.state = {
            name: 'React',
            apiData: [],
            canAdmin: false,
            history: history,
        };
    }

    canAdmin() {
        console.log('Can Admin: ' + this.state.canAdmin)
        return this.state.canAdmin;
    }

    componentDidMount() {
        console.log('app mounted');        
        
        const tokenString = sessionStorage.getItem("token");
        const token = JSON.parse(tokenString);
        this.setState({ canAdmin: token.canAdmin})

        fetch(Config.apiUrl + "/api/Header/GetLogo")
            .then(data => data.json())
            .then(data => this.setState({ image: "data:image/png;base64," + data.image }, () => console.log(data)));
        fetch(Config.apiUrl + "/api/Header")
            .then(data => data.json())
            .then(data => this.setState({ header: data }, () => console.log(data)));
    }


    render() {
        const logoImage = this.state.image;
        const myHeader = this.state.header;
        
        return (
            <div>
                <Helmet>
                    <title>{myHeader?.title}</title>
                </Helmet>
                <Jumbotron fluid>
                    <Container fluid id="headerContainer">
                        <img src={logoImage} id="logoImg" />
                        <input id="searchBar" type="text" placeholder="Search"></input>
                        {console.log('Location: ' + this.state.history.location.pathname)} <<== Error here
                        <NavLink to='/portal' isActive={() => this.canAdmin()}>
                            <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" className="bi bi-person" viewBox="0 0 16 16">
                                <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0zm4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4zm-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664h10z" />                            
                            </svg>
                        </NavLink>
                        <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="currentColor" className="bi bi-cart" viewBox="0 0 16 16">
                            <path d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
                        </svg>
                    </Container>
                </Jumbotron>
            </div>
        );
    }

}
export default LogoHeader;

I am getting an error that this.state.history is undefined in the line {console.log('Location: ' + this.state.history.location.pathname)}.

Upvotes: 3

Views: 42

Answers (2)

Yogesh Yadav
Yogesh Yadav

Reputation: 863

React Router Docs

history objects typically have the following properties and methods: location - >(object) The current location. May have the following properties: pathname - (string) >The path of the URL

    const LogoHeader = ({ history }) => {
    return (
           if (history.location.pathname === '/') <a href="/portal" / >
           if (history.location.pathname === '/portal') <a href="/" / >
           )
    }

Also if it give errors then don't forget to export your LogoHeader component using withRouter.

import { withRouter } from "react-router-dom";
export default withRouter(LogoHeader );

Upvotes: 2

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

I suggest reading the documentation. There are several ways, but the easiest in your case might be to just use the useLocation or even useRouteMatch hook.

Upvotes: 0

Related Questions