简体   繁体   中英

How can i remove a Property from a react component on router path change

I am trying to Have a navbar that is transparent on the landing page but i don't want it to be transparent when I am on other pages. is there a way to do that or should i try another method?

render() {
return (
  <>
    {
      Route.path === '/' ? <Header transparent={this.state.transparent} /> : <Header />
    }

    <Switch>
      <Route path='/' exact component={Home} />
      <Route path='/aboutus' component={AboutUs} />
      <Route path='/shop' component={Shop} />
    </Switch>
    <Footer />
  </>
);

}

I want to do something like this or a way to remove the transparent property when the path is different

Here is the state

constructor(props) {
super(props)
this.state = {
  transparent: true,
}
this.listener = null}

and the rest of the code is

componentDidMount() {
this.listener = document.addEventListener('scroll', e => {
  let scrolled = document.scrollingElement.scrollTop;
  if (scrolled >= 150) {
    if (this.state.transparent !== false) {
      this.setState({ transparent: false});
    }
  } else {
    if (this.state.transparent !== true) {
      this.setState({ transparent: true});
    }
  }
});

}

  componentDidUpdate() {
document.removeEventListener("scroll", this.listener);

}

what can i do here guys?

To determine current path use useLocation().pathname hook. For this you need react-router-dom of version 6.x (dont know if works even on 5.x) and then code should look like:

const pathname = useLocation().pathname
render(
...
{
pathname === '/' ? a : b
}
...
)

You can accomplish this a few ways. The easiest is probably to use the useRouteMatch hook in your Header component to test for the route you want the header to behave differently on.

const Header = () => {
  const match = useRouteMatch({
    pathname: '/',
    exact: true
  });

  return (
    ... JSX ... apply transparent logic on match
  );
}

App

render() {
  return (
    <>
      <Header />
      <Switch>
        <Route path='/aboutus' component={AboutUs} />
        <Route path='/shop' component={Shop} />
        <Route path='/' component={Home} />
      </Switch>
      <Footer />
    </>
  );
}

Alternatively, if Header isn't a function component you either render directly on a Route , or decorate with the withRouter Higher Order Component, and check the location prop. In Header in the render lifecycle method check this.props.location.pathname .

render() {
  const { location } = this.props;
  const isTransparent = location.pathname === "/";

  return (
    ... JSX ... apply transparent logic
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM