React Functional Component Props Syntax Options

Mindwatering Incorporated

Author: Tripp W Black

Created: 05/01 at 05:05 PM

 

Category:
NodeJS
Reference

There are multiple options for passing Props from parent functional Components to (or up from) children functional Components


The Props "props" could be a single variable or an object of multiple Props. In the example below it is an object with multiple variables inside it.

function Profile(props) {
let pNm = props.pNm;
let pEmail = props.pEmail
let pAddrSt = props.pAddrSt
let pAddrState = props.pAddrState
let pAddrCode = props.pAddrCode
...
}


Another way to express it is with "destructuring" shortcut, where the props are a JavaScript object with the {} inside the braces ().

function Profile( {pNm, pEmail, pAddrSt, pAddrState, pAddrCode} ) {
// no variable const/let assignments needed
...
}


We can give defaults to the functional component at the same time to save entry time. Below, we have added a default for the state variable.

function Profile( {pNm, pEmail, pAddrSt, pAddrState=NC, pAddrCode} ) {
// no variable const/let assignments needed, state is equal to NC, but can be overwritten
...
}


If we are going to pass all the props, without adding new ones, such as when the parent Component is a wrapper object, we can use a "spread" to pass them to the children Components. In the below example, we import three components and render them with the props they all share in common.

import AcctInfoCard from './AcctInfoCard.js';
import AcctHistory from './AcctHistory.js';
import AcctCurrentWork from './AcctCurrentWork.js';

function Profile(props) {
return (
<div className="card">
<AcctInfoCard {...props} />
</div>
<div className="card">
<AcctHistory {...props} />
<AcctCurrentWork { ...props} />
</div>
);
}



Besides being a variable value or an object, the props variable can contain the JSX of the children Components. This technique is common for layout flex grids and panels when the parent panel Components do not need to know what they contain.

import AcctInfoCard from './AcctInfoCard.js';
import AcctHistory from './AcctHistory.js';
import AcctCurrentWork from './AcctCurrentWork.js';

function Panel({ children }) {
<div className="panel">
{children}
</div>
}

export default function Profile(props) {
return (
<Panel>
<div className="card">
<AcctInfoCard {...props} />
</div>
<div className="card">
<AcctHistory {...props} />
<AcctCurrentWork { ...props} />
</div>
</Panel>
);
}





previous page

×