Exporting multiple non functional components in React js

Viewed 85

I am trying to create a component Book, which has a header, and I want to be able to import it in App.js as shown in the code below, I am fairly new to react and I do not know how to look up for it because I don't know how this concept is called. How can make a component Book and that component has other non functional components such as Book.Header for a header book or Book.Title, and that I can use as shown in the App.js

const Book = () => (
  <div className="book">
    <Book.Header />
  </div>
);

Book.Header = ({child}) => (
  <div><p>{child}</p></div> // here should render the text from Book.Header in App.js
);

export default Book;

And in App.js

import Book from "./components/Book";
function App() {
  return (
    <div className="App">
      <Book
        <Book.Header>My book header</Book.Header> // I want to render this in 
         // Book.Header 
      >
      </Book>
    </div>
  );
}
2 Answers

It has to be Class based component in order to extend the functionality of that component, in this case your Book component would look something like this:

class Book extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      header: this.props.children // path to children
    };
  }
  render() {
    const { header } = this.state;
    return (
      <div>
        <Book.Header header={header}/>
      </div>
    );
  }
}

Book.Header = ({header}) => (
  <div>
    <p>{Header}</p>
  </div>
);

Book & Header

const Book = () => (
  <div className="book">
    <Book.Header />
  </div>
);

Book.Header = () => (
  <div><p>This is the header</p></div>
);

module.exports = { Book, Header };

And the App.js

const Book = require = ("./components/Book");
function App() {
  return (
    <div className="App">
      <Book.Book
        <Book.Header>My book header</Book.Header>
      >
      </Book.Book>
    </div>
  );
}

Try this. I am not fully sure about the require part if it works in React, it does in my Node apps. If it does not work, look into how to import the exported modules via the "module.exports = ..." way :)

Related