What are React “Props”?
In React, we can use Props (similar to HTML attributes) to pass data or functions to components.
Examples of “Attributes”
Assume we have the following object:
export const CORE_CONCEPTS = [
{
image: componentsImg,
title: 'Components',
description:
'The core UI building block - compose the user interface by combining multiple components.',
},
{
image: jsxImg,
title: 'JSX',
description:
'Return (potentially dynamic) HTML(ish) code to define the actual markup that will be rendered.',
},
{
image: propsImg,
title: 'Props',
description:
'Make components configurable (and therefore reusable) by passing input data to them.',
},
{
image: stateImg,
title: 'State',
description:
'React-managed data which, when changed, causes the component to re-render & the UI to update.',
},
];
There are different ways to pass Props. We can individually pass the object and use “destructuring”:
<CoreConcept
title={CORE_CONCEPTS[0].title}
description={CORE_CONCEPTS[0].description}
image={CORE_CONCEPTS[0].image} />
export default function CoreConcept({ concept }) {
// Use concept.title, concept.description etc.
// Or destructure the concept object: const { title, description, image } = concept;
}
Alternatively, we can pass the object completely:
<CoreConcept
{...CORE_CONCEPTS[0]} />
export default function CoreConcept({ ...concept }) {
//..concept groups multiple values into a single object
// Use concept.title, concept.description etc.
//Or destructure the concept object: const { title, description, image} = concept;
}
“Children Props”
It is also possible to set data using the children prop. The following example illustrates the difference:
//Children Variante
<TabButton>Components</Tabbutton>
function TabButton({children}){
return <button>{children}</button>;
}