简体   繁体   中英

Passing react-router-dom Link component as a render prop is failing

I'm trying to pass a react-router-dom Link component as a render prop to a component, but am running into some issues:

https://codesandbox.io/embed/xjm35923qo

The error that I receive when passing <Link>hi</Link as a render prop is Invariant Violation Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Invariant Violation Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

That seems fair enough, but if I instead pass in something like () => <Link>hi</Link> , there is no error, but there is a warning ( react-dom.development.js?7f13:507 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. ) and the link doesn't render.

I'm having trouble wrapping my head around these error messages -- what am I missing here?

You should import Link as a named import:

import {Link} from "react-router-dom"

and you need to wrap your app with a Router object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM