DEV Community

Cover image for Spread Multiple Props With This Syntax
Daniel Bellmas
Daniel Bellmas

Posted on

Spread Multiple Props With This Syntax

In React, when working with components, you might encounter scenarios where you want to conditionally pass multiple props based on a certain condition. Fortunately, there's a concise syntax that allows you to do just that.

The Conditional Spread Syntax

Imagine you have a React component named <Button />, and you want to conditionally pass multiple props (color and size) to it based on some condition. Here's how you can achieve this using the conditional spread syntax:

function App() {
  const [isLoading, setIsLoading] = useState(false)

  return (
      {/* Conditional spreading of props */}
      <Button {...(isLoading && { color: 'primary', size: large })}>
        Click me
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. We first define a condition in this example it's isLoading that determines whether we want to pass the additional props.
  2. We define the color and size variables, which represent the props we want to conditionally pass to the <Button /> component.
  3. Within the JSX, we use the conditional spread syntax:

{...(isLoading && { color, size })}.

  • If the condition is true, it spreads the object { color, size } as props to the <Button /> component.
  • If the condition is false, no props are spread, and the <Button /> component receives only its default props.
  1. We render the <Button /> component with the conditional props, and it will have the additional properties (color and size) only when the condition is met.

This technique provides a clean and concise way to conditionally spread multiple props onto a component, making your code more readable and maintainable when you have varying prop requirements based on specific conditions.

Top comments (0)