Components in ReactJS

A not-so-deep dive into a difficult topic of component.
When I started learning React the first new term I came across was component. It is the first thing one should learn about. Basically, a component is a Javascript class or function that has props for the parameters passes to them and returns JSX which is rendered in the react DOM. Or in more simpler language, components are the reason why your UI is interactive and exists on the first place.
Look at the top of the page! I mean it, to the extreme top of this page. See the header and navbar? Chances are it has its own component.
Now there are two categories of components:-
- Class Component
- Functional Component
Class Component
class MyClass extends Component
{
render()
{
return(<div>Just skip this one</div>);
}
}
export default MyClassClassComponent;
In case you missed an obvious Easter egg, here in the code the render method which has return containing JSX, this will be rendered in the browser.
Functional Component
We have all seen it from the time we started learning ReactJS. But regardless we shall have to see the code because your boi has pages to fill.
function SimpleFunction
{
return(<div>Stick to this</div>);
}
export default SimpleFunction;
Here directly the JSX is returned and rendered in the browser, whenever this particular function is called or invoked.
props: passing data to components
Passing data to components is done through props. For this let us have a look at this code:
const Hello = (props) => {
return (
<div>
<p>Hello {props.name}</p>
</div>
)
}
const App = () => {
return (
<div>
<h1>Greetings</h1>
<Hello name="Pink guy"/>
</div>
)
}
Now the function defining the component has a parameter props. As an argument, the parameter receives an object, which has fields corresponding to all the "props" the user of the component defined i.e. name. There can be an arbitrary number of props and their values can be "hard coded" strings or results of JavaScript expressions. If the value of the prop is achieved using JavaScript it must be wrapped with curly braces.
return (
<div>
<h1>Greetings</h1>
<Hello name="Pink guy" age={16 + 6} />
</div>
)
The props sent by the component App are the result of the evaluation of the sum expression and a regular string.
Hopefully this blog has fulfilled its sole purpose.
I know this is a plain one with nothing interesting to maintain your attention at this blog unlike the previous one.


