How to change the value of a defaultProps in a React component?

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 in the same way, without changing the default value.

How do I change the value?

Thank you for your attention.

    
asked by anonymous 04.08.2017 / 17:47

1 answer

2

You have not declared 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'
}

Because 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>
  );
    
15.08.2017 / 16:31