Categories: React Development
Tags:

To show an image placeholder when props.image is not provided or is undefined, you can set up a default image URL as a fallback within the component. This can be done directly in the JSX code using a conditional check or by setting a default value in the component.

Here’s how you can do it:

Method 1: Inline Conditional Rendering

In the JSX, you can check if props.image exists; if not, use a placeholder URL.

function ProfilePicture(props) {
  return (
    <img
      src={props.image ? props.image : 'path/to/placeholder.jpg'}
      alt="Profile"
    />
  );
}

Method 2: Destructure with Default Value

Alternatively, destructure props with a default image value.

function ProfilePicture({ image = 'path/to/placeholder.jpg' }) {
  return <img src={image} alt="Profile" />;
}

Method 3: Using Default Props (for Class Components or Legacy Functional Components)

If you’re using an older version of React or class components, you can use defaultProps:

function ProfilePicture(props) {
  return <img src={props.image} alt="Profile" />;
}

ProfilePicture.defaultProps = {
  image: 'path/to/placeholder.jpg',
};

In Summary

The conditional check can be done directly in the src attribute, or you can set a default value for image. This ensures the placeholder image is shown whenever props.image is missing or undefined.