Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering a function when entering a route (react-router-dom)

const Main = () => (
  <div>
    <Header />
    <StyledMain>
      <Header />
      <Switch>
        <Route exact path="/" component={Splash} render={()=>{alert('dd"')}}/>
        <Route path="/files" component={Files} />
        <Route path="/archived" component={Archived} />
        <Route path="/extract/:filename" component={Extract} />
        <Route path="/docs/api" component={Docs} />
      </Switch>
    </StyledMain>
  </div>
)

In my main.js, I tried to trigger an alert whenever I enter the main route ('/'). However, this does not work.

I also tried onEnter, but realized that this is for the older version.

Is this the right usage?

like image 584
Dawn17 Avatar asked Mar 05 '23 18:03

Dawn17


1 Answers

You can put alert in your Splash component as @Tholle suggested in the comment. But with render you can do this without using component:

const Main = () => (
  <div>
    <Header />
    <StyledMain>
      <Header />
      <Switch>
        <Route exact path="/" render={() => {
                alert('dd"');
                return <Splash />;
            }
        }/>
        <Route path="/files" component={Files} />
        <Route path="/archived" component={Archived} />
        <Route path="/extract/:filename" component={Extract} />
        <Route path="/docs/api" component={Docs} />
      </Switch>
    </StyledMain>
  </div>
)
like image 135
devserkan Avatar answered Apr 27 '23 17:04

devserkan