Understanding React Components and Props
Q. What are react components?
Ans: React components are JavaScript functions that return markup (JSX). A components has its own logic and appearance.
All react components are made with composition of components. A component can nest other component.
Q. What are props?
Ans: React components uses props to communicate with each other. A parent component pass props to it's child component as an information to it. A props can be any valid JavaScript type like, string, number, object, array, function etc.
Props are read-only, every render receives a new version of props.
You can’t change props. When you need interactivity, you’ll need to update state.
/* Note here I am destructuring props here directly.*/
const Child = ({ name, address }) => {
return <div>
<div>{name}</div>
<div>{address}</div>
</div>
}
const Parent = () => {
/*Here we are passing info to Child component,
we can also pass objects, arrays etc.
*/
return <Child name="test" address="Address" />
}
In React we get one special prop called children
when we wrap a component inside the other component, e.g.
const Child = ({ name, address, children }) => {
return <div>
<div>{name}</div>
<div>{address}</div>
<div>{children}</div>
</div>
}
const Parent = () => {
/* The Avatar component will be passed as children props to Child component*/
return <Child name="test" address="Address">
<AvatarComponent/>
</Child>
}