I am training how to use default props and I ran into a problem. Can anyone explain to me why default props doesn't work in this case?
import React from 'react';
import PropTypes from 'prop-types';
import defaultImage from '../../../assets/DefaultImageOnError.svg'
export const ImageComponent = ({ props }) => {
return (
<img width={ props.size } src={ props.src } alt={ props.alt }/>
);
};
ImageComponent.propTypes = {
props: PropTypes.objectOf(PropTypes.string),
};
ImageComponent.defaultProps = {
props: {
size: '150px',
src: defaultImage,
alt: 'error'
}
}
When I turn off props for this component in another file. The component should load defaultprops. Why is this not happening?
Props is an object, when you do { props } you are accessing props.props instead of props.
Just replace
export const ImageComponent = ({ props }) => {
and
ImageComponent.defaultProps = {
props: {
size: '150px',
src: defaultImage,
alt: 'error'
}
}
With
export const ImageComponent = (props) => {
const {size, src, alt} = props;
or
export const ImageComponent = ({size, src, alt}) => {
...
And update propTypes to match (this is probably a typo in your exmaple):
ImageComponent.defaultProps = {
size: '150px',
src: defaultImage,
alt: 'error'
}
To simplify this, and prevent these kinds of mistakes in the future, consider using object destructuring to set defaults instead:
export const ImageComponent = (props) => {
const {
size = '150px',
src = defaultImage,
alt = 'error',
} = props;
or
export const ImageComponent = ({
size = '150px',
src = defaultImage,
alt = 'error',
}) => {
...