logo
Back to blogs

React Components with Default Props

Mar 10, 2023 - 2 min read

React Components with Default Props

The Problem: Managing Props Dynamically

In real-world applications, React components often need to handle a wide range of inputs (props) that influence their appearance or behavior. For example:

  • A button component might need to change its size, color, or disabled state based on certain conditions
  • A form field could adjust its placeholder text or validation rules dynamically.

While these customizations make components powerful, they can also lead to problems. Developers may forget to set certain props or pass incorrect values, causing the component to behave unexpectedly.

The Solution: Default Props

Default props are a powerful feature in React that allow you to define default values for a component’s props. When a prop is not provided by the parent component, React automatically uses the default value instead. This ensures that the component always has the necessary data to render correctly, even if the parent component forgets to pass certain props. Here’s a simple example of setting default props in a functional React component:

default-props-example.tsx
1import Button from "./components/button"; 2import { Loading, Warning } from "./components/icons"; 3 4export default function App() { 5 return ( 6 <> 7 <Button type="primary" icon={<Loading color="white" />} /> 8 <Button type="secondary" icon={<Loading />} /> 9 <Button icon={<Loading />} /> 10 </> 11 ); 12} 13const Button= ({ 14 type, 15 icon, 16 size, 17 disabled, 18}: { 19 type?: string; 20 icon: ReactElement; 21 size?: string; 22 disabled?: string; 23})=> { 24 const defaultProps= { 25 size: size= "lg" ? "lg" : "md", 26 color: type= "primary" ? "white" : "black", 27 }; 28 const newProps= { 29 ...defaultProps, 30 ...icon.props, 31 }; 32 if (disabled) { 33 newProps.color= "gray"; 34 } 35 const clonedIcon= React.cloneElement(icon, newProps); 36 return <button>Submit {clonedIcon}</button>; 37}; 38export default Button; 39export const Loading = ({ size, color }: { size?: string; color?: string }) => { 40 return <span style={{ fontSize: size, color: color }}></span>; 41}; 42export const Error = () => { 43 return <span></span>; 44}; 45export const Warning = () => { 46 return <span>⚠️</span>; 47}; 48export const Avatar = () => { 49 return <span>😎</span>; 50};