craftdeer
craftdeer

Reputation: 1025

React rendering unnecessary component in my app

New to react and working with React Router so that I have many pages. I am in my Home.jsx and it looks like this.

    import React, { Component } from 'react';
    import randomimage from '../imagefolder/rentalbackground.jpg';
    import Header from './Header';
    import Footer from './Footer';
    import Rentals from './Rentals';
    import {
      BrowserRouter as Router,
      Route,
      Redirect,
      Link
   } from 'react-router-dom';

    class Home extends Component {
      render() {
        return (
        <div>
            <Header />
            <Router>
                <div>
                    <Link to="/rentals">Rentals</Link>
                    <main>
                        <Route path="/" component={Rentals} />
                    </main>
                </div>
            </Router>
            <p>some paragraph here</p>
            <img src={randomimage} alt="imagerand" />
            <Footer />
        </div>
    );
   }
  }
export default Home;

And my Rentals component looks like this.

    import React, { Component } from 'react';
    class Rentals extends Component {
     render() {
      return (
        <div>
            <p>this is for all the rentals</p>
        </div>
             )
            }
           }
   export default Rentals;

What I am trying to do is create a page called localhost:3000/rentals which only displays the paragraph from the "Rentals" component in a new page. But when I click on the rentals link, which is on the Home.jsx, it displays all the components from the "Home" component including the picture, and the Header and the Footer components too.
I tried using exact path on the Route and nothing happens. How might I achieve this?

Upvotes: 2

Views: 137

Answers (1)

codeslayer1
codeslayer1

Reputation: 3686

This is because you have placed your Router component inside your Home component which in turn have your Header and Footer. So all child components will be rendered inside your Home component.

Your router component should be on the top level of your App and all other components like Home, Rentals etc should be added as a child to the router.

Just to give you an example, it should be something like this.

//Your app initialisation, Top Level
 ReactDOM.render(
    <div style={{height: '100%'}}>

      //All Your routes can be exported at one place and passed to your router as props. This will also help you maintain routes at one place
      <Router history={browserHistory} children={routes}/>

    </div>,
    document.getElementById('root')
  )

Will suggest you to read more about using React router and best practices since this is an architecture problem and quite broad topic to be answered here.

Upvotes: 1

Related Questions