0

I am trying to display input value on submit. But it seems to be not working. I don't have any errors but nothing being rendered. What is wrong with the code?

import React from 'react';
import { Component } from 'react';

class App extends Component {
    constructor (props) {
        super(props)
        this.state = {
            city : ""
        }
          
    }
        
    handleSubmit = (event)=> {
        event.preventDefault();
        this.setState ({
          city : event.target.value 
        })
          }
     
    render () {
        return (
         <div>
            <form  onSubmit={this.handleSubmit}>
             <input type = "text" city = "city_name" />
             <button type="submit">Get Weather</button>
            {this.state.city}
             </form>
         </div>
        )
    }
}

export default App;
skyboyer
  • 22,209
  • 7
  • 57
  • 64

3 Answers3

0

I guess you want it to get work like below. But this is not the only way to get it done.

import React from "react";
import { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      city: ""
    };
  }

  handleSubmit = (event) => {
    const formData = new FormData(event.currentTarget);
    event.preventDefault();
    let formDataJson = {};
    for (let [key, value] of formData.entries()) {
      formDataJson[key] = value;
    }
    this.setState(formDataJson);
  };

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input type="text" name="city" />
          <button type="submit">Get Weather</button>
          {this.state.city}
        </form>
      </div>
    );
  }
}

export default App;

Code sandbox => https://codesandbox.io/s/eager-oskar-dbhhu?file=/src/App.js

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
0

Remember onSubmit target:
Indicates where to display the response after submitting the form. So you can get inner elements (and their corresponding values) like normal javascript code.

const city = event.target.querySelector('input').value

handleSubmit = (event) => {
   event.preventDefault();
   this.setState ({ city })
}
amirhe
  • 2,186
  • 1
  • 13
  • 27
  • this one helped! Thank you! – Yoqubxon Xamidoff Nov 06 '21 at 18:19
  • Hey @YoqubxonXamidoff , make sure to subscribe and hit the bell to get the latest notification, just kidding ;) happy to hear that it helped you. If you found the answer helpful you can upvote it or mark it as an answer with check and arrow icons on the left – amirhe Nov 06 '21 at 18:22
0
      <form 
           onSubmit={e=>{
                e.preventDefault()
                console.log(e.target[0].value)
            }}>
            <input type="text"/>
            <button type="submit">dg</button>
      </form>

that works for me very well

Samira
  • 2,361
  • 1
  • 12
  • 21