How to pass component as a Prop in React.js?

How to use Components in React.js?ยป

Then, go to index.js file and import LayoutSection by adding:

import LayoutSection from './LayoutSection';

Now, you want to put NewsSection component inside the LayoutSection component. A component can be broken down as: <LayoutSection></LayoutSection>. Inside of these, you are going to pass NewsSection component as a prop, for instance:

<LayoutSection>
<NewsSection
newsTitle="Earthquake hits Tokyo with 6.5, 14 dead, 5 injured"
newsDate="May 20 2019"
newsSummary="News summary 1"
newsImg={Faker.image.city()}
/>
</LayoutSection>

Do the same for other two news sections as well, such the index.js file looks like:

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

const App = () => {
return (
<div className="container">
<LayoutSection>
<NewsSection
newsTitle="Earthquake hits Tokyo with 6.5, 14 dead, 5 injured"
newsDate="May 20 2019"
newsSummary="News summary 1"
newsImg={Faker.image.city()}
/>
</LayoutSection>

<LayoutSection>
<NewsSection
newsTitle="Iran dismisses possibility of conflict in War"
newsDate="May 19 2019"
newsSummary="News summary 2"
newsImg={Faker.image.people()}
/>
</LayoutSection>

<LayoutSection>
<NewsSection
newsTitle="Top 10 benefits of eating Apples in morning"
newsDate="May 18 2019"
newsSummary="News summary 3"
newsImg={Faker.image.food()}
/>
</LayoutSection>

</div>

);
};

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

This means, you can now accept this prop (NewsSection) inside LayoutSection.js file. Go to LayoutSection.js file and accept the prop as:

const LayoutSection = (props) => {
...
}

After that, use { props.children } where you want the NewsSection to be displayed:

<p className="card-text">
{props.children}
</p>

The LayoutSection.js file should now look like this:

import React from 'react';

const LayoutSection = (props) => {
return (
<div className="card">
<div className="card-body">
<p className="card-text">
{props.children}
</p>
<button className="btn btn-primary">Like</button> &nbsp;
<button className="btn btn-primary">Comment</button> &nbsp;
<button className="btn btn-primary">Share</button> &nbsp;
</div>
</div>
);
};

export default LayoutSection;

Save the file, open your browser, and you should have something like this:

const LayoutSection = (props) => {
...
}

Leave a Comment