Reputation: 19
I was trying to make a simple react weather app and it worked but not properly because before add the material-ui button it was working perfect and now it is working only if i click enter not click on the button because the material-ui const city = e.target.elements.city.value;
this code is not working with it at all
here is the form component is like
return (
<div>
<form onSubmit={props.getWeather}>
<p>Just type the city name </p>
<p className="check">you must spelling correctly</p>
<TextField
id="standard-basic"
name="city"
placeholder="City....."
variant="outlined"
/>
<Button onClick={props.getWeather} variant="contained" color="primary">
find
</Button>
</form>
</div>
);
};
export default Form;
and in the app component
getWeather = async e => {
e.preventDefault();
const city = e.target.elements.city.value;
const api = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}`
);
const data = await api.json();
Upvotes: 0
Views: 2326
Reputation: 2648
Remove onClick handler from button and add type="submit", so it'll work both in case of Enter click and button click:
<Button type="submit" variant="contained" color="primary">
find
</Button>
It's going to work only when your button is in hierarchy of <form>
type="submit" simply submits the form.
Upvotes: 3