How to check if a component prop is a function in React?
class MyComponent extends React.Component {
render() {
return <h1>if (typeof this.props.showName === 'function') {
//call this.props.showName(d)
}
}
}
Your above code seems fine. But your approach is wrong.
You need to validate props using propTypes
MyComponent .propTypes = {
showName : React.PropTypes.func
};
Here is the other checks,
propArray: React.PropTypes.array.isRequired,
propBool: React.PropTypes.bool.isRequired,
propFunc: React.PropTypes.func,
propNumber: React.PropTypes.number,
propString: React.PropTypes.string,
propObject: React.PropTypes.object
React.PropTypes has moved into a different package since React v15.5. Please use the prop-types library instead.
import PropTypes from 'prop-types';
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Greeting.propTypes = {
name: PropTypes.string
};
Write it like this:
checkMethod(){
if(typeof(this.props.showName) === 'function') {
//call this.props.showName(d);
return null;
}else{
return this.props.showName;
}
}
class MyComponent extends React.Component {
render() {
return
<h1>
{this.checkMethod()}
</h1>
}
}
}