How to change the value of a defaultProps on an React component?

Asked

Viewed 901 times

0

Good afternoon,

I have a loading component that uses a default props.

class Loading extends Component {
  render() {
    const loadingClasses = classNames({
      'loading': this.props.loading,
    })

    return (
      <div className={loadingClasses}>
        {this.props.loading === 'loading-inline' && <i className='fa fa-spinner fa-spin mr2' />}
        <FormattedMessage id='loading' />
      </div>
    )
  }
}

Loading.propTypes = {
  loading: PropTypes.string,
}

Loading.defaultProps = {
  loading: 'loading'
}

I want to use this component elsewhere, and change the value of this props. So I used it as follows:

 <Loading loading='loading-inline' />

Only the component is rendered the same way, without changing the default value.

How do I change the value?

Thank you for your attention.

1 answer

2


You did not declare the constructor and passed the props to your class:

class Loading extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    const loadingClasses = classNames({
      'loading': this.props.loading,
    })

    return (
      <div className={loadingClasses}>
        {this.props.loading === 'loading-inline' && <i className='fa fa-spinner fa-spin mr2' />}
        <FormattedMessage id='loading' />
      </div>
    )
  }
}

Loading.propTypes = {
  loading: PropTypes.string,
}

Loading.defaultProps = {
  loading: 'loading'
}

Since your component does not use this.state, you can create a functional Component:

const Loading = ({ loading }) => { // desestruturação do objeto props
  const loadingClasses = classNames({
    'loading': loading,
  });

  return (
          <div className={loadingClasses}>
            {loading === 'loading-inline' && <i className='fa fa-spinner fa-spin mr2' />}
            <FormattedMessage id='loading' />
          </div>
  );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.