How do I export more than one class component with React JS?

Tony Carbetta picture Tony Carbetta · Apr 28, 2018 · Viewed 31.2k times · Source

I'm new to React and would like to keep all my components in one file. How do I export more than one component and keep them in the same file?

    import React, { Component } from "react";

class MyText extends Component {
  render() {
    return (<div>
      <h1>
        Component</h1>
      <p>This class component is named MyText. I can re-use it's code by simply Rendering (fancy name for calling) it by it's class name and I won't have to re type it, however many times I will need it.</p>
    </div>);
  };
}

class GreetName extends Component {
  render() {
    return (
      <div>
       <h1>Hello, {this.props.name}</h1>;
       </div>
    );
  };
}

export default MyText;

Answer

Denys Kotsur picture Denys Kotsur · Apr 28, 2018

You can do as Jess Kenney said or use naming export at the bottom of your file:

SomeComponent.js

import React, { Component } from "react";

class MyText extends Component {
  render() {
    return (<div>
      <h1>
        Component</h1>
      <p>This class component is named MyText. I can re-use it's code by simply Rendering (fancy name for calling) it by it's class name and I won't have to re type it, however many times I will need it.</p>
    </div>);
  };
}

class GreetName extends Component {
  render() {
    return (
      <div>
       <h1>Hello, {this.props.name}</h1>;
       </div>
    );
  };
}

export { MyText, GreetName };

And then use it like:

import { MyText, GreetName } from './SomeComponent'

I advice you to use one component per file, so you can keep your project modular. In ReactJS it's a convention to export one component from a file, and to export it is as the default export.

If it's helper component which used only in the particular you can put it to the same file as functional component.