Piotr Perak Piotr Perak - 1 month ago 12
React JSX Question

Mixing default and named imports changes how code works

Sometimes I see imports like this

import React, { PropTypes} from 'react'
and it doesn't cause any problems.

But when I try to do this in my code
import Router, { hashHistory } from 'react-router'
my render call doesn't render anything.

When I change it to
import { Router, hashHistory } from 'react-router'
then it works.

What's the rule here? When can I import with and without
{}
in same import statement and when I can't? Looking into
react-router
code it does export
Router
as defult.

QoP QoP
Answer

You can import without {} when a module defines a export default

react-router doesn't have any export default.

https://github.com/ReactTraining/react-router/blob/master/modules/index.js

export Router from './Router'
export Link from './Link'
export IndexLink from './IndexLink'
export withRouter from './withRouter'

/* components (configuration) */
export IndexRedirect from './IndexRedirect'
export IndexRoute from './IndexRoute'
export Redirect from './Redirect'
export Route from './Route'

/* utils */
export { createRoutes } from './RouteUtils'
export RouterContext from './RouterContext'
export { locationShape, routerShape } from './PropTypes'
export match from './match'
export useRouterHistory from './useRouterHistory'
export { formatPattern } from './PatternUtils'
export applyRouterMiddleware from './applyRouterMiddleware'

/* histories */
export browserHistory from './browserHistory'
export hashHistory from './hashHistory'
export createMemoryHistory from './createMemoryHistory'

Maybe you were looking into the code of an old version of react-router which used to have an export default

Version 1.0.x

/* components */
export Router from './Router'
export Link from './Link'
export IndexLink from './IndexLink'

/* components (configuration) */
export IndexRedirect from './IndexRedirect'
export IndexRoute from './IndexRoute'
export Redirect from './Redirect'
export Route from './Route'

/* mixins */
export History from './History'
export Lifecycle from './Lifecycle'
export RouteContext from './RouteContext'

/* utils */
export useRoutes from './useRoutes'
export { createRoutes } from './RouteUtils'
export RoutingContext from './RoutingContext'
export PropTypes from './PropTypes'
export match from './match'

export default from './Router'