Home > Blockchain >  How do I then render a function in my route using the v6 react-router-dom
How do I then render a function in my route using the v6 react-router-dom

Time:07-16

I am new to react development and currently undergoing a tutorial on react routes that uses V5 react-router-dom. I am finding it difficult to render a function in my routes now that I am using v6 react-router-dom. I need help as other solutions I am seeing online advice I use hooks which I am not yet familiar with.

import React, { Component } from 'react';
import { Route, Routes } from "react-router-dom";
import DogList from './DogList';
import DogDetails from './DogDetails';
import whiskey from './images/whiskey.jpg';
import tubby from "./images/tubby.jpg";
import hazel from "./images/hazel.jpg";
import './App.css';

class App extends Component {
  static defaultProps = {
    dogs: [ 
      {
        name: "Whiskey",
        age: 5,
        src: whiskey,
        facts: [
          "Whiskey loves eating popcorn.",
          "Whiskey is a terrible guard dog.",
          "Whiskey wants to cuddle with you!"
        ]
      },
      {
        name: "Hazel",
        age: 3,
        src: hazel,
        facts: [
          "Hazel has soooo much energy!",
          "Hazel is highly intelligent.",
          "Hazel loves people more than dogs."
        ]
      },
      {
        name: "Tubby",
        age: 4,
        src: tubby,
        facts: [
          "Tubby is not the brightest dog",
          "Tubby does not like walks or exercise.",
          "Tubby loves eating food."
        ]
      }
    ]
  };
  render() {

How do I then render the getDog function in my route using the v6 react-router-dom.

    const getDog = props => {
      let name = props.match.params.name;
      let currentDog = this.props.dogs.find(
        dog => dog.name.toLowerCase() === name.toLowerCase()
      );
      return <DogDetails {...props}  dog={currentDog}/>
    }
    return (

I get this error that "/dogs/Hazel" does not have an element ". Then When I then change the render to element, I get a different error saying Functions are not valid as a React child.

     <Routes>
       <Route 
         exact
         path='/dogs'
         element={<DogList dogs={this.props.dogs} />}
       />
    

       <Route  exact path='/dogs/:name' render={getDog}/>
     </Routes>
    );
  }
}


export default App;

CodePudding user response:

You need to use nested routes.

     <Routes>
       <Route exact path='dogs' element={<DogList dogs={this.props.dogs} />}
             <Route path=':name' element={getDog}/>
       </Route>
     </Routes>
    );
  }
}


export default App;

CodePudding user response:

change your route like this and try again. is it ok now?

<Route exact path='/dogs/:name' element={<getDog/>}/></Routes>

  • Related