Categories
Uncategorized

Composition in React

Composition in React allows to import components from another function while we write normal HTML is one function. It is mainly of two types:

1) Containment:

One of its example is where WelcomeDialog function has normal HTML code, while other function FancyBorder helps to add two classes ‘FancyBorder FancyBorder-blue’ to div outside this code.

A) Here is function with normal HTML code:

function WelcomeDialog() {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
Welcome
</h1>
<p className="Dialog-message">
Thank you for visiting our spacecraft!
</p>
</FancyBorder>
);
}

B) Here is function which fetches props ‘color’ from FancyBorder component in WelcomeDialog() function and adds classes ‘FancyBorder FancyBorder-blue’ to a div outside FancyBorder in WelcomeDialog() function by calling (or containing) its internal code through {props.children}.

function FancyBorder(props) {
return (
<div className={'FancyBorder FancyBorder-' + props.color}>
{props.children}
</div>
);
}

Output can be seen through ReactDOM:

ReactDOM.render(
<WelcomeDialog />,
document.getElementById('root')
);

Another example can be seen here.

2) Specialization: In this multiple functions specializes in different works. 

Here is an example, similar to above program:

A) First there is function which creates border: 

function FancyBorder(props) {
return (
<div className={'FancyBorder FancyBorder-' + props.color}>
{props.children}
</div>
);
}

B) Here is function which provides overall HTML structure: 

function Dialog(props) {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
{props.title}
</h1>
<p className="Dialog-message">
{props.message}
</p>
</FancyBorder>
);
}

C) Here is function which uses above two functions and adds title & message text: 

function WelcomeDialog() {
return (
<Dialog
title="Welcome"
message="Thank you for visiting our spacecraft!" />
);
}

D) Here is output generated: 

ReactDOM.render(
<WelcomeDialog />,
document.getElementById('root')
);

Here is another program example of specialization.

Leave a Reply

Your email address will not be published. Required fields are marked *