Having issues getting the Material UI button to work in ReactJS

While creating a simple react weather app, I encountered an issue. The app was functioning perfectly until I added a material-ui button. Now, the app only works when I press enter and not when I click on the button. It seems that the material-ui code

const city = e.target.elements.city.value;
is causing the problem. Here is the form component:

  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();

Answer №1

Replace the onClick handler with type="submit" in your button element, allowing it to function with both Enter key presses and mouse clicks:

<Button type="submit" variant="contained" color="primary">
   find
</Button>

This modification will work effectively when the button is within a <form> element as type="submit" triggers form submission.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The best way to close a swipeable drawer from a different class

I'm feeling a bit puzzled by the explanation of SwipeableDrawer on the Material-ui website. Here's the setup I have: there's a Component called 'Sidebar' that opens a SwipeableDrawer when a user clicks a button on the appbar or swi ...

Tips for ensuring that Breadcrumbs are displayed properly with the noWrap feature

I am currently working on making the MUI component Breadcrumbs responsive. The issue I am facing is that when the Breadcrumbs component fills up all available space, the items shrink and use ellipsis like a Typography component with the noWrap property se ...

The function 'next build' is malfunctioning when attempting to create a build for my nextJS application

While attempting to create a nextJS application, I encountered a recurring issue: next build - info Creating an optimized production build - info Compiled successfully - info Linting and checking validity of types - info Collecting page data [ ] - ...

Unveiling the Theme: Navigating the Material UI withStyles and WithTheme for Theme

const StyledSlider = withStyles({ root: { color: theme => theme.palette.primary.main } }, { withTheme: true })(Slider); Initially, I thought the withTheme option would allow access to the theme inside the withStyles function. However, since the t ...

How do you vertically span a grid element across 3 rows using Material UI?

This particular scenario may appear to be straightforward, but the official documentation of Material UI lacks a clear example on how to achieve this. Even after attempting to nest the grid elements, I encountered an issue where the grid element on the ri ...

What is the best way to retrieve the primaryText value within the onChange function of a SelectField component?

I am trying to access the primaryText from the onChange method of SelectField. However, onChange only provides (event,index,value). Here is my code snippet: <SelectField value={props.value} onChange={this.handleChange}> {props.opt ...

The component 'ProtectRoute' cannot be utilized within JSX

While using typescript with nextjs, I encountered an issue as illustrated in the image. When I try to use a component as a JSX element, typescript displays the message: ProtectRoute' cannot be used as a JSX component. import { PropsWithChildren } from ...

Encountering a TypeError with Arg 1 while trying to execute the save method in jsPDF

I am currently working on a react project with a simple implementation of jsPDF. I am trying to execute the sample 'hello world' code but encountering an error when using the save method: https://i.stack.imgur.com/o4FWh.png My code is straightf ...

What could be the reason for my component not getting the asynchronous data?

Currently, I am delving into the intricacies of React and have been following a tutorial that covers creating components, passing props, setting state, and querying an API using useEffect(). Feeling confident in my understanding up to this point, I decided ...

Unable to trigger enzyme test click event on a material ui Checkbox within a redux-form Field component

I am currently working on setting up an enzyme/mocha/chai test to replicate the scenario where the state of a materialUI Checkbox component changes from true to false. The Checkbox is enclosed within a redux-form Field, and I am facing difficulties in simu ...

Animating the Click Event to Change Grid Layout in React

Can a grid layout change be animated on click in React? For instance, consider the following component: import { Box, Button, styled, useMediaQuery } from "@mui/material"; import Row1 from "./Row1"; import React from "react"; ...

How do you display a nested object in React after merging it?

To display the JSON below as an image, click https://i.stack.imgur.com/tixu4.png let finalSplit = [ { start: "73", end: "76", splits: [ { word: "Now", start: "73", ...

Cannot locate module: Error: Unable to find the path '../containers/Layout' in '/home/yusquen/Projectss/react-shop/src/components'

https://i.stack.imgur.com/U1097.png description of image goes here Issue with module: Error: The file '../containers/Login' could not be found in the 'react-shop/src/components' directory. ...

Refreshing a React form

this.state = { name: "", arr: [], story: "" }; add(e) { e.preventDefault(); this.setState({ story: e.target.value }); this.state.arr.push(this.state.story); this.form.reset(); } <form action=""> <input onChange={this.b} type="t ...

Issue alert before running tests on component that includes a Material UI Tooltip

This is a follow-up regarding an issue on the Material-UI GitHub page. You can find more information here. Within my Registration component, there is a button that is initially disabled and should only be enabled after accepting terms and conditions by ch ...

What is the process for integrating the Bootstrap JS library into a Next.js project?

My upcoming project involves server-side rendering with Next.js, and I plan to incorporate Bootstrap into it. After some research, I decided to import Bootstrap into my root layout like this: import { Inter } from "next/font/google"; import " ...

Error encountered while trying to import the Turborepo UI package into Next.js: It appears that an appropriate loader may be required

Currently, I am working on a project using next.js 13.1.1 and setting up a monoRepo-based project with turborepo for the first time. My goal is to incorporate: @next/bundle-analyzer @sentry/nextjs @next-pwa When these configurations are not used, everyth ...

Fixing NextJS ReferenceError: Request undefined due to using outdated Node version

Whenever I execute npm run dev in my Next.js project, an error pops up: .../node_modules/next/dist/server/web/spec-extension/request.js:28 class NextRequest extends Request { ^ ReferenceError: Request is not defined at Object ...

Tips for showcasing the information from a JSON document in React

I have a JSON file stored statically in my public directory and I'd like to show its content within a React component (specifically NextJS). The goal is to simply render the JSON as it is on the page. import data from '../../public/static/somedat ...

Combining v1 and "next" versions in Material UI for optimal performance

Is it possible to seamlessly integrate the newly released "next" components from the "next" branch of Material UI with our current v1 components, and gradually transition our legacy components to the "next" as they are released? Are there any compatibili ...