Skip to content
react

How to conditionally add props to React component

Jul 8, 2022Abhishek EH3 Min Read
How to conditionally add props to React component

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:

App.js
1import React, { useState } from "react"
2import Box from "./Box"
3
4const App = () => {
5 const [weight, setWeight] = useState(10)
6 return <Box showExtraCharge={weight > 10 ? true : false} />
7}
8
9export 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:

App.js
1import React, { useState } from "react"
2import Box from "./Box"
3
4const App = () => {
5 const [weight, setWeight] = useState(10)
6 return <Box showExtraCharge={weight > 10} />
7}
8
9export default App

Using if statement

We can rewrite the above code using if statement as follows:

App.js
1import React, { useState } from "react"
2import Box from "./Box"
3
4const App = () => {
5 const [weight, setWeight] = useState(10)
6 let showExtraCharge = false
7 if (weight > 10) {
8 showExtraCharge = true
9 }
10 return <Box showExtraCharge={showExtraCharge} />
11}
12
13export 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:

App.js
1import React, { useState } from "react"
2import Box from "./Box"
3
4const App = () => {
5 const [weight, setWeight] = useState(10)
6 const [type, setType] = useState("T001")
7 return <Box showExtraCharge={weight > 10 && type === "T002"} />
8}
9
10export 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

App.js
1import React, { useState } from "react"
2import Box from "./Box"
3
4const App = () => {
5 const [weight, setWeight] = useState(10)
6 return <Box {...(weight > 10 && { showExtraCharge: true })} />
7}
8
9export 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!

© 2024 CodingDeft.Com