I know there is a lot of posts on this topic but i havent found one with elements passed as parameters and i dont know how to do it without declaring a function. I dont understand why react tells me this error as i thought it was only saying this when the react component invoked does not contain react component structure/elements/requirements.
My MainComponent.js code is as follow: (i'm passing parameters to the route /menu/:dishId with a const DishWithId)
import {Navbar,NavbarBrand} from 'reactstrap';
import React, { Component } from 'react';
import { useState } from "react";
import Menu from './MenuComponent';
import Footer from './FooterComponent';
import {DISHES} from '../shared/dishes'
import Dishdetail from './DishdetailComponent';
import Home from './HomeComponent';
import Contact from './ContactComponent'
import {Routes,Route,Navigate} from 'react-router-dom';
import Header from './HeaderComponent'
import {COMMENTS} from '../shared/comments';
import {LEADERS} from '../shared/leaders';
import {PROMOTIONS} from '../shared/promotions';
class Main extends Component {
constructor (props){
super (props);
this.state = {dishes: DISHES, comments: COMMENTS, promotions: PROMOTIONS, leaders: LEADERS};
}
render(){
const shouldRedirect=true;
const HomePage=()=>{
return (
<Home dish={this.state.dishes.filter((dish)=>dish.featured)[0]}
promotion={this.state.promotions.filter((promotion)=>promotion.featured)[0]}
leader={this.state.leaders.filter((leader)=>leader.featured)[0]}
/>
);
}
const DishWithId=({match})=>{
return (
<Dishdetail dish={this.state.dishes.filter((dish) => dish.id === parseInt(match.params.dishId, 10))[0]}
comments={this.state.comments.filter((comment) => comment.dishId === parseInt(match.params.dishId, 10)[0])}/>
);
}
return (<div className="App">
<Header />
<Routes>
<Route exact path='/menu' element={<Menu dishes={this.state.dishes}/> }/>
<Route path="/menu/:dishId" element={DishWithId}/>
<Route path='/home' element={<HomePage/>}/>
<Route exact path='/contactus' element={<Contact/>}/>
<Route path='/' element={
shouldRedirect ? (<Navigate replace to="/home" />) : (<HomePage />)
}/>
</Routes>
<Footer/>
</div>);
}
}
export default Main;
I get the error when i go to http://localhost:3000/menu/0 I tried to use render() but i didnt manage to make it work. Note this code was supposed to work with previous version of react where component was in place of element (it comes from a mooc)...
CodePudding user response:
You'll need to change the route
<Route path="/menu/:dishId" element={DishWithId}/>
To:
<Route path="/menu/:dishId" element={<DishWithId />}/>
And update your DishWithId
to use the useParams
hook for getting the dishId
, like:
const DishWithId=({match})=>{
const { dishId } = useParams()
return (
<Dishdetail dish={this.state.dishes.filter((dish) => dish.id === parseInt(dishId, 10))[0]}
comments={this.state.comments.filter((comment) => comment.dishId === parseInt(dishId, 10)[0])}/>
);
}