Accepted answer

I believe that defaultProps should do what you need:

import PropTypes from 'prop-types';

class AppButton extends Component {
    return (
      <button onClick={this.props.onClick}>{this.props.message}</button>

AppButton.propTypes = {
  message: PropTypes.string,
  onClick: PropTypes.func

AppButton.defaultProps = {
  message: 'Hello',
  onClick: function(){ alert("Hello"); }

From the docs:

The defaultProps will be used to ensure that will have a value if it was not specified by the parent component. The propTypes typechecking happens after defaultProps are resolved, so typechecking will also apply to the defaultProps.

Edit for clarity: There should be no need for you setMessage in this instance.


You cant set props, you must use state instead.

If you need to change the value, then it should be stored in the state due to props are static.

You should do it in this way:

this.setState({message: 'your message'});

And in the render method use it as:


As a recomendation, you should also initialize the state with that value in the constructor:


  this.state = {
    message: ''

The same will happend to setOnClick

You will find here a good explanation about this.


for deafault props you can do this

 const { 
     message = '', 
     onClick = (e)=>{} 
 } = props;

and use these variables without props keyword (you can still use props for not defined props values)

<button onClick={onClick}>{message}</button> 

But for your error it is just fine to handel error like:

{props.message ?? ''}


Are you using React v.14 or above? the props object is now frozen and cant be changed. You can use React.cloneElement instead


return (
      <button onClick={this.props.onClick}>{this.props.message || "Default text"}</button>

This will check the value of prop and if it is undefined or null, the default message will replace the prop.

Related Query

More Query from same tag