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