How to conditionally add props to React component

Last updated on May 28, 2021 by Suraj Sharma



In this tutorial, you will learn how you can conditionally add or remove props to a component in React.


props as object


We can define React component props as an object and pass the object to the called component using spread operator(...)


Example


<Component title="React" label="library" />

// can be rewritten as 

const props = {
  title: 'React',
  label: 'library'
}

<Component {...props} />


So, to conditionally add or remove some of the props you can use JavaScript ternary operator(a?b:c) or the if-else statement, like the way I have done in the below examples.


Example 1

//using ternary operator
const App = () => {

  const [isShowDescription, setIsShowDescription] = useState(false);

  const customProps = {
    label: "Hello",
    size: 100 
  }
  return (
    <CustomComponent
      { ...customProps }
      {...(
        isShowDescription ?
        { description: 'added description property' } :
        {}
      )}
    />
  );
}

export default App;


Example 2

//using if-else statement
const App = () => {

  const [isHeight, setIsHeight] = useState(false);
  const boxProps = {}

  if (isHeight) {
    boxProps.height = "200px";
  }

  return (
    <Box 
      { ...boxProps }
    />
  );
  
}

export default App;


Conclusion


In this tutorial, you have learnt how you can represent props as an object, pass the object to React components using spread operator(...), and conditionally add or remove props using JavaScript ternary operator.



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.