Table of Contents
Have you ever wanted to pass props to a child component only if certain conditions are met? Then you are at the right place. In this article, we will see 4 different ways of achieving the same.
Using ternary operator
We can use ternary operator to evaluate the expression and pass the result as a prop as shown below:
1import React, { useState } from "react"2import Box from "./Box"34const App = () => {5 const [weight, setWeight] = useState(10)6 return <Box showExtraCharge={weight > 10 ? true : false} />7}89export default App
When the weight is more than 10 showExtraCharge
will be passed as true
, otherwise false
.
Since the expression itself evaluates into a boolean, we can shorten the code as shown below:
1import React, { useState } from "react"2import Box from "./Box"34const App = () => {5 const [weight, setWeight] = useState(10)6 return <Box showExtraCharge={weight > 10} />7}89export default App
Using if statement
We can rewrite the above code using if statement as follows:
1import React, { useState } from "react"2import Box from "./Box"34const App = () => {5 const [weight, setWeight] = useState(10)6 let showExtraCharge = false7 if (weight > 10) {8 showExtraCharge = true9 }10 return <Box showExtraCharge={showExtraCharge} />11}1213export default App
Here we are creating a new variable showExtraCharge
and setting the value to it and passing it to the child component.
The above code makes it more clear what is happening. However, it may not be suitable if there are many props since we need to create as many local variables.
Using && operator
If there are 2 conditions to be checked, then we can use the && operator:
1import React, { useState } from "react"2import Box from "./Box"34const App = () => {5 const [weight, setWeight] = useState(10)6 const [type, setType] = useState("T001")7 return <Box showExtraCharge={weight > 10 && type === "T002"} />8}910export default App
In the above code, showExtraCharge
will be passed as true only if both the weight is greater than 10 and the type is T002
.
Using spread operator
If you need a prop to be passed only of a certain condition is met, you can use the spread operator as shown below
1import React, { useState } from "react"2import Box from "./Box"34const App = () => {5 const [weight, setWeight] = useState(10)6 return <Box {...(weight > 10 && { showExtraCharge: true })} />7}89export default App
Now the Box
component will receive the prop showExtraCharge
only when the weight is more than 10.
If the weight is greater than or equal to 10 then the prop showExtraCharge
will not even be passed to the Box
component.
Do follow me on twitter where I post developer insights more often!