1
votes

I just started learning react and ran into a problem when I tried to use react-router-dom I ran into a problem that only the first component is rendered for all routes defined

Here is HomePage.js that defines the routes

import React, { Component } from 'react';
import Categories from "./categories";
import Category from "./category";
import ListingItem from "./listing_item";
import { 
BrowserRouter as Router, 
Switch, 
Route, 
Redirect, 
Link 
} from 'react-router-dom';

export default class HomePage extends Component{
constructor(props){
    super(props);
}

render() {
return (
  <Router>
    <Switch>
      <Route exact path="" component={ListingItem}/>
      <Route path="categories/" component={Categories}/>
      <Route path="category/" component={Category}/>
      </Switch>
  </Router>
);
}}

I tried the "category" and "categories" components with the exact path and without the exact and still only the first component is rendered

Here are the components: listing_item component

import React, { Component } from 'react';

export default class ListingItem extends Component{
    constructor(props){
        super(props);
    }

    render() {
        return <p>This is the Item Listing page</p>
    }
}

category

import React, { Component } from 'react';

export default class Category extends Component{
    constructor(props){
        super(props);
    }

    render() {
        return <p>This is a single Category page</p>
    }
}

and categories is the same structure

Here is App.js that renders Homepage

import React, {Component} from "react";
import { render } from "react-dom";
import HomePage from "./HomePage";


export default class App extends Component {
    constructor(props){
        super(props);
    }


    render() {
        return(
            <div>
                <HomePage />
            </div>
            );
    }
}
const AppDiv = document.getElementById("app");
render(<App />, AppDiv)
1
Put path="/" from your home page and put path="/categories" / must be in beginning of your route name.Sayog
Is there a way to solve this without changing the URLs because this is a Django app and I need to keep the URLs like that as when I change them I get into another error where nothing is rendered at all, not even the first componentAhmad Hamdy

1 Answers

0
votes

You have a syntax issue that might cause the problem.

export default class category extends Component

should be

export default class Category extends Component{

and

export default class listing_item extends Component

should be

export default class ListingItem extends Component