How to pass props in React Components correctly?

Viewed 640

I have routes array, which pass into RouteComponent

const info = [
  { path: '/restaurants/:id', component: <Restaurant match={{ params: '' }} /> },
  { path: '/restaurants', component: <ListRestaurant match={{ path: '/restaurants' }} /> }
];

I use Axios for connection with back-end

Restaurant Component:

  async componentDidMount() {
    this.getOne();
  }
  getOne() {
    const { match } = this.props;
    Api.getOne('restaurants', match.params.id)

Restaurant Component:

When I see console there is en error like this enter image description here

So, what can be passed as the props? Can't find solution. Thanks in advance

App.js

import ...
import info from './components/info/routes';

class App extends Component {
  render() {
    const routeLinks = info.map((e) => (
      <RouteComponent
        path={e.path}
        component={e.component}
        key={e.path}
      />
    ));
    return (
      <Router>
        <Switch>
          {routeLinks}
        </Switch>
      </Router>
    );
  }
}

RouteComponent.js

import { Route } from 'react-router-dom';

class RouteComponent extends Component {
  render() {
    const { path, component } = this.props;
    return (
      <Route path={path}>
        {component}
      </Route>
    );
  }
}

RouteComponent.propTypes = {
  path: PropTypes.string.isRequired,
  component: PropTypes.object.isRequired,
};

EDITED 22/03/2020

Line with gives this: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of Context.Consumer.

class RouteComponent extends Component {
  render() {
    const { path, component } = this.props;
    return (
      <Route path={path} component={component} />
    );
  }
}

RouteComponent.propTypes = {
  path: PropTypes.any.isRequired,
  component: PropTypes.any.isRequired,
};

But as you see, I make PropTypes 'any'

2 Answers

Ok there are some changes you will need to do and might not be enough. So let me know if does not work in comments.

Step one

send component correctly to routes

class RouteComponent extends Component {
  render() {
    const { path, component } = this.props;
    return (
      <Route path={path} component={component}/>
    );
  }
}

Step two

Send JSX element, not JSX object

const info = [
  { path: '/restaurants/:id', component: Restaurant },
  { path: '/restaurants', component: ListRestaurant }
];

Import RouteProps from react-router-dom and use it as the interface for props in routecomponent.js.

Then, instead of calling component via expression, call it like a component, i.e.

Eg,

function Routecomponent({ component: Component, ...rest }: RouteProps) {
    if (!Component) return null;

    return (
        <Route
            {...rest}
                <Component {...props} />
               />}
    )
}
Related