I have this code:
class Sidebar extends Component {
render() {
return (
<div className="sidebar">
{ this.props.children }
</div>
);
}
}
class Item extends Component {
render() {
return (
<div>
<b> { this.props.name } </b>
</div>
);
}
}
export { Sidebar, Item };
export {default as Header} from './Header';
export {default as Footer} from './Footer';
export {default as Sidebar, Item} from './Sidebar';
import { Sidebar } from '../components';
class App extends Component {
render() {
return (
<div>
<Header/>
<Sidebar>
<Sidebar.Item name='item1' />
<Sidebar.Item name='item2' />
<Sidebar.Item name='item3' />
</Sidebar>
<Footer/>
// ...
The error that I get is:
TypeError: Cannot read property 'Item' of undefined
How I can multiple export component in index.js
and call from another file? I'm sure that Header and Footer work correctly because I have only one class in that file.
function Sidebar(props) {
return (
<div className="sidebar">
{ props.children }
</div>
);
}
function Item (props) {
return (
<div>
<b> { this.props.name } </b>
</div>
);
}
Sidebar.Item = {Item}
export default Sidebar
Then you can use it like this
import Sidebar from './Sidebar.js'
...
return (
<Sidebar>
<Sidebar.Item />
</Sidebar>
)
If you're using class based components, you can remove the curly braces
class Sidebar extends Component {
render() {
return (
<div className="sidebar">
{this.props.children}
</div>
);
}
}
class SidebarItem extends Component {
render() {
return (
<div>
<b> {props.name} </b>
</div>
);
}
Sidebar.Item = SidebarItem;
export default Sidebar;
I learned this practice from a coworker that saw it in semantic ui's table here.
Have you tried
import { Item } from '../components';
and then use it:
<Item name='item1' />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With