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;
0, React allows us to return multiple elements from the render function by wrapping them in an array. In previous versions, it was necessary to wrap multiple elements into a single parent, which resulted in an extra node appearing in the DOM tree.
Use named exports to export a component in React, e.g. export function Button() {} . The exported component can be imported by using a named import as import {Button} from './another-file. js' . You can use as many named exports as necessary in a file.
To export multiple functions in JavaScript, use the export statement and export the functions as an object. Alternatively, you can use the export statement in front of the function definitions. This exports the function in question automatically and you do not need to use the export statement separately.
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.
Instead of using the export default
line at the bottom, you can put export before each class definition, like export class GreetName...
then to include your classes in another file you can use import {MyText, GreetName} from 'your/file.js'
export default secretContext;
export {taskData};
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