Reputation: 2586
Trying to get an onClick function working in react with a form , however, it isnt working but using a button does.
The following code works with the button but not the input. I'm wondering what I might be
<CustomInput
onChange={(v) => setLastName(v)}
label="Last Name*"
invalid={
(lastName || validate) &&
!yup.string().required().isValidSync(lastName)
}
value={lastName}
onClick={() => alert('hello')}
/>
<button onClick={() => alert('hello')}>Click me!</button>
Upvotes: 1
Views: 6127
Reputation: 329
This is probably happening because you didn't use the onClick prop anywhere inside CustomComponent. When you passed the onClick prop to the button, React knows that it has to create a button and attach an onclick event listener to it which fires off your alert when the button is clicked. However, when you pass the onClick prop to CustomComponent, since React innately doesn't know what CustomComponent is, it doesn't create a component immediately. It first accesses your CustomComponent's source file, and creates DOM elements according to CustomComponent's render method's return. Any props that were passed to CustomComponent can be accessed it. When passing props in this manner, React assumes that onClick is just another name for a prop, and doesn't understand that you want it to attach an eventListener to the wrapper element in the return statement of CustomComponent's render method. You will have to manually attach this inside CustomComponent.
for example,
CustomButton.js
import React from 'react';
const CustomButton = props => {
return (
<div>
<button>Click me</button>
</div>
);
};
export default CustomButton;
App.js
import './App.css';
import CustomButton from './CustomButton';
function App() {
return (
<div className="App">
<CustomButton onClick={()=>alert("Clicked")}/>
</div>
);
}
export default App;
In the above case, nothing happens when button is clicked, because there is no onClick in CustomButton.js
However, if this is done:
CustomButton.js
import React from 'react';
const CustomButton = props => {
return (
<div onClick={props.onClick}>
<button>Click me</button>
</div>
);
};
export default CustomButton;
Now, the alert will appear when the button is clicked(or rather, when the div is clicked).
The name of the prop passed to CustomButton needn't have been onClick either, as the word has no significance when used on a custom component.
App.js
import './App.css';
import CustomButton from './CustomButton';
function App() {
return (
<div className="App">
<CustomButton anyprop={()=>alert("Clicked")}/>
</div>
);
}
export default App;
CustomButton.js
import React from 'react';
const CustomButton = props => {
return (
<div>
<button onClick={props.anyprop}>Click me</button>
</div>
);
};
export default CustomButton;
This works just fine as well, so long as the names of the prop being passed in CustomButton and App match.
Upvotes: 3