Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
101
rated 0 times [  104] [ 3]  / answers: 1 / hits: 25621  / 7 Years ago, mon, february 13, 2017, 12:00:00

I want to pass a function to a component as a prop and use it in its render function, I seem to be missing a key concept here.



For example



index.jsx



render(<MyComponent d={data} showName = {d => d.name + ' ' + d.surname}/>, document.getElementById('app'));


MyComponent.jsx



class MyComponent extends React.Component {
render() {
return <h1>if (typeof this.props.showName === 'function') {
//call this.props.showName(d)
}
}
}


edit



I want the showName prop to be either a function or a value and the component doesn't need to know about it beforehand.



edit2



On second thought, I think I'll build a component so it can use both a function and a value as a prop, but keep them separate so that I can validate them better. E.g. I'll either use



<MyComponent value=some value/> 


or



<MyComponent calculatedValue = {// a function}/>

More From » reactjs

 Answers
14

https://facebook.github.io/react/docs/typechecking-with-proptypes.html



You can do it like this and if it's not a function it will tell you:



     MyComponent.propTypes = {
showName: React.PropTypes.func.isRequired
};


This is the react way to do it ;)



Edit: I got it now, you can do an assertion on the prop by calling it with an argument, if the assertion fails, you'll know it's not a function. Check this package on npm, it's easy to use it out of the box



https://www.npmjs.com/package/assert


[#58958] Friday, February 10, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kourtney

Total Points: 368
Total Questions: 103
Total Answers: 85

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
kourtney questions
Sun, Oct 4, 20, 00:00, 4 Years ago
Tue, Oct 29, 19, 00:00, 5 Years ago
Thu, Apr 4, 19, 00:00, 5 Years ago
Fri, Mar 1, 19, 00:00, 5 Years ago
;