Let's look at three different ways to pass props to a React Js component. Passing props depends on the method signature of the React component receiving props.
My component DisplayTable accepts props as defined in the DisplayTableProps interface
interface DisplayTableProps {
name: string
salary: number
position: string
}
export const DisplayTable = (props: DisplayTableProps) =>{
return(
<>
<div>{props.name}</div>
<div>{props.salary}</div>
<div>{props.position}</div>
</>
)
}
There are a few ways I can pass props to my DisplayTable component.
import { DisplayTable } from "./components/SuccessMessage"
export const App = () => {
return(
<>
<DisplayTable
name="Lance"
salary={130000}
position="Software Engineer"
/>
</>
)
}
I can create an object that contains the same properties as the DisplayTableProps.
const employee = {name: "Tomoyuki", salary: 140000, position: "Engineering Manager"}
Then I can spread it and pass it to my component.
<DisplayTable {...{...employee}}/>
I can create the object inline and pass it to the component. But the object properties must match with the interface DisplayTableProps.
<DisplayTable {...{name: "Tomoyuki", salary: 140000, position: "Engineering Manager"}}/>
Here my component accepts an object type DisplayTableProps.
interface DisplayTableProps {
name: string
salary: number
position: string
}
type Props = {
employee: DisplayTableProps
}
export const DisplayTable = ({employee}: Props) =>{
return(
<>
<div>{employee.name}</div>
<div>{employee.salary}</div>
<div>{employee.position}</div>
</>
)
}
In this case, the usage is less verbose. I only have to pass the object reference to the component.
import { DisplayTable } from "./components/SuccessMessage"
export default const App = () => {
return(
<>
<DisplayTable employee={employee}/>
</>
)
}
I also can spread and pass an inline object like the one below.
<DisplayTable {...{employee:{name: "Tomoyuki", salary: 140000, position: "Engineering Manager"}}}/>
In this scenario, my component only uses a subset of properties defined in the DisplayTableProps interface. I de-struct the props and used only the salary and the name. This method is identical to method 1.
interface DisplayTableProps {
name: string
salary: number
position: string
}
export const DisplayTable = ({name, salary}:DisplayTableProps) =>{
return(
<>
<div>{name}</div>
<div>{salary}</div>
</>
)
}
Note that I must still pass the complete set of properties even though the component doesn't use them.
import { DisplayTable } from "./components/SuccessMessage"
export const App = () => {
return(
<>
<DisplayTable {...{name: "Jeff", salary: 150000, position: "Director"}}/>
</>
)
}
I also can create an object, spread it and pass it as props
const employee = {name: "Jeff", salary: 150000, position: "Director"}
<DisplayTable {...{...employee}}/>
Passing individual properties is also an option.
<DisplayTable
name="Lance"
salary={130000}
position="Software Engineer"
/>