1

I have my application looking something like below..

import FirstComponent from "./components/firstComponent";
import NextComponent from "./components/nextComponent";
import MyProgressComponent from "./components/progressComponent";

class App extends React.Component {
render() {
  return (
    <Router>
        <div>
            <MyProgressComponent />
            <Route path="/" exact component={FirstComponent} />
            <Route path="/nextComponent" component={NextComponent} />   
        </div>
    </Router>
  );
}
}

As we can see 'MyProgressComponent' is visible when we navigate between 'http://localhost:3000/' and 'http://localhost:3000/nextComponent' because it is directly nested under Router component in App component. But I want 'MyProgressComponent' to be visible only in 'http://localhost:3000/nextComponent' and hidden in 'http://localhost:3000/'. Any suggestion ?

I can do this by importing 'MyProgressComponent' inside each component wherever required but I don't want to duplicate it in each component.

2
  • 2
    if you don't want to import it in every file, you just add a condition that makes MyProgressComponent not displaying when the path is / Commented Sep 11, 2019 at 6:32
  • and you can do one thing that you can import MyProgressComponent inside the NextComponent Commented Sep 11, 2019 at 6:39

3 Answers 3

1

You can render multiple components using the below syntax

<Route path="/nextComponent" render={() => 
 <>
  <MyProgressComponent />
  <NextComponent />
 </>
} 
/> 
Sign up to request clarification or add additional context in comments.

1 Comment

Nice I like this solution too
0

Based on @Crocsx comment you can apply following check on your code.

<Router>
  <div>
    {this.props.location.pathname === "/nextComponent" ?  <MyProgressComponent />: null}
    <Route path="/" exact component={FirstComponent} />
    <Route path="/nextComponent" component={NextComponent} />
  </div>
</Router>

Comments

0

you can use switch provided by router to achieve this.

Something like below should work for you.

<Switch>
  <Route exact path="/nextComponent" component={MyProgressComponent} />
</Switch>
<Switch>
  <Route path="/" exact component={FirstComponent} />
  <Route path="/nextComponent" component={NextComponent} /> 
</Switch>

more documentation is available here https://reacttraining.com/react-router/web/guides/basic-components

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.