How to export and import components in React.js?

How to use Components in React.js?»

Finally you have created a NewsSection.js file that contains the NewsSection component. However, the component you’ve created cannot be directly accessed by index.js file even if both the files are inside the same directory.First, you need to export the NewsSection component from NewsSection.js file. And by export, I really mean it. After exporting, you need to import the component inside index.js file.

To export the component, go to NewsSection.js file and add the following code at the bottom of the file:

export default NewsSection;

This will make NewsSection component available to the rest of the project.

To import the component, go to index.js file and add the following code to the top of the file:

import NewsSection from ‘./NewsSection’;

This extra ./ ensures that the file you’re looking for (NewsSection.js) is present inside the same directory as the current file (index.js).

Now it’s time to use this component inside your index.js file. You need to clean all the code between <div className=”row”></div> these tags, because you’re going to use components for the same instead. Modify the file so it looks like:

import React from 'react';
import ReactDOM from 'react-dom';
import NewsSection from './NewsSection';

const App = () => {
return (
<div className="container">
<NewsSection/>
</div>
);
};

ReactDOM.render(<App/>, document.querySelector("#root"));

You’d notice that you’re only using <NewsSection/> where you want the NewsSection component to appear. When you nest one component inside another component, you use </> tag.

To show this component multiple times, just call the component name as many times as you want it to appear in the browser:

const App = () => {
return (
<div className="container">
<NewsSection/>
<NewsSection/>
<NewsSection/>
</div>
);
};

This will display three news sections on the browser.

Leave a Comment