Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple export with dot notation

I have this code:

Sidebar.jsx

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 };

index.js

export {default as Header} from './Header';
export {default as Footer} from './Footer';
export {default as Sidebar, Item} from './Sidebar';

app.jsx

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.

like image 462
Kaiser69 Avatar asked Feb 26 '18 20:02

Kaiser69


2 Answers

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.

like image 88
Galupuf Avatar answered Sep 21 '22 23:09

Galupuf


Have you tried

import { Item } from '../components';

and then use it:

<Item name='item1' />

like image 36
aherriot Avatar answered Sep 20 '22 23:09

aherriot