React JS ES6: import modules
ReactJS import modules
1 Overview
📘 **import modules*
The magic of components lies in their reusability: you can create components that are composed of other components.
But as you nest more and more components, it often makes sense to start splitting them into different files. This lets you keep your files easy to scan and reuse components in more places.
2 Exporting and importing a component
What if you want to change the landing screen in the future and put a list of science books there? Or place all the profiles somewhere else? It makes sense to move Gallery and Profile out of the root component file.
This will make them more modular and reusable in other files. You can move a component in three steps:
- Make a new
JS fileto put the components in. Exportyour function component from that file (using eitherdefaultor namedexports).Importit in the file where you’ll use the component (using the corresponding technique forimportingdefault ornamed exports).
Here both Profile and Gallery have been moved out of App.js into a new file called Gallery.js. Now you can change App.js to import Gallery from Gallery.js:
Gallery.js
function Profile() {
return (
<img
src="https://i.imgur.com/QIrZWGIs.jpg"
alt="Alan L. Hart"
/>
);
}
export default function Gallery() {
return (
<section>
<h1>Amazing scientists</h1>
<Profile />
<Profile />
<Profile />
<p>I love science!! Do you know what does STEAM mean? Come on, Albertus, answer the question! </p>
</section>
);
}App.js
