Categories
Uncategorized

Properties & Components in React.JS

Elements can represent user defined components with properties (props), which can be passed to a function. ‘props’ are read-only. A component can be any particular thing. Let us see example below: 

const element = <Welcome class="New" />

Here we created a component ‘Welcome’ whose property value is ‘New’. Remember to use first letter capital for function or component name (React.JS is case-sensitive language). Now we will use this property in function using component name ‘Welcome’ and ‘props’: 

function Welcome(props){
return <h1> Its, {props.class}. </h1>;
}

In the end, we render the element: 

ReactDOM.render(
element,
document.getElementById('root')
);

It shows output:

Its, New.


We can create a function App, which has many Welcome components with different properties. For example:

function App(){
return (
<div>
<Welcome class = "This is" />
<Welcome class = "Its" />
</div>
)
}

Now let us use these components’ properties dynamically once in another function:

function Welcome(props) {
return <h1> {props.class} New. </h1>;
}

Now render the output:

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

Its creates output:

This is New.

Its New.


Extracting components: We can create multiple components in the form of JavaScript variables however they need to be extracted during rendering, so that extracted values can be seen in structure. Let us create JavaScript variables first:

const comment = {
date: new Date(),
text: 'I hope you enjoy learning React!',
author: {
name: 'Hello Kitty',
avatarUrl: 'https://placekitten.com/g/64/64',
},
};

We can modify the date variable value to fetch date similar to a user’s time zone:

function formatDate(date) {
return date.toLocaleDateString();
}

Now let us create a function to create overall structure of output:

function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img
className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">{props.text}</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}

Props variables used above can’t show output until we extract them as shown below, while rendering output:

ReactDOM.render(
<Comment
date={comment.date}
text={comment.text}
author={comment.author}
/>,
document.getElementById('root')
);

Extracted variables in above shows that these should be fetched from a function whose name is ‘comment’ (starting with small ‘c’) and put them in function ‘Comment’ (starting with capital ‘c’).


 

Leave a Reply

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