Reputation: 304
This is a simplified example of what I am trying to do. What I wanted to be able to do is to pass the functions to different components of React via props. I can pass text to props, and call the function directly by doing <button onClick={popup}>
but that is not the purpose of my experiment. The onClick doesn't trigger the function, and there is 'uncaught' error in console.log when rendering which is not helpful.
const Elem = (props) =>{
return (<div>
<h1> hi {props.name} {props.last} phase two </h1>
<button onClick={props.clickon}> {props.text} </button>
</div>
);
};
function popup(){
alert("It works!")
}
class App extends React.Component{
constructor(props) {
super(props);
}
render(){return (<Elem name = 'paul' last='shreeman' clickon='popup' text='PushMe'/>
)
}}
ReactDOM.render(
<App />, document.getElementById('root'))
Here's the link to the codepen: https://codepen.io/pkshreeman/pen/GENmaG?editors=0010
Upvotes: 1
Views: 440
Reputation: 104379
Reason is, you are not passing the function
you are passing a string, to pass a function
you need to write it like this:
clickon = {popup}
Now it will pass the function popup
, not the string "popup"
.
Full code:
class App extends React.Component{
constructor(props) {
super(props);
}
render(){
return (
<Elem name='paul' last='shreeman' clickon={popup} text='PushMe'/>
)
}
}
Check the working code: https://codepen.io/anon/pen/MobvqB?editors=0010
Check this answer for details about what's the meaning of {}
:
What do curly braces mean in JSX (React)?
Upvotes: 3