How to store and pass the user input value using <button> tag in React.js?

135
April 10, 2018, at 05:16 AM

So I'm trying to get the value from the user and show it on the screen, but it seems my code doesn't pass the value from my Input class to the main class. Nothing happens when I click Submit. here is the code for my main .js class:

import React, { Component } from 'react';
import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';
class App extends Component {
  state = {
    userName : 'Masood'
  }
  manipulator = (event) => {
    this.setState(
      {userName : event.target.value}
    )
  }

  render() {
    return (
      <div>
        <UserOutput userName = {this.state.userName}/>
        <UserInput changed={this.manipulator}/>
      </div>
    );
  }
}
export default App;

Here is the code for the Input class:

import React from 'react'
const userInput = (props) => {
    return(
        <div>
        <form onSubmit={props.changed}>
            <input style={style} type="text" value={props.userName}/>  
            <input type="submit" value="Submit"/>   
        </form>
        </div>
    )
};
export default userInput;

and here is the output class:

import React from 'react'
    const userOutput = (props) => {
        return(
        <div>
         <p> Here is a test from output file.</p>
         <p>Username is {props.userName}</p>
        </div>
        )
    };
export default userOutput;

Sorry for a too long code for a too small question, but I thought I should include everything.

Answer 1

I would assume the main problem is that you try to submit a value, but if you console.log the event.target.value it is equal to null.

You should have an event handler for `onChange, when you change the text in the input, f.e:

const UserInput = props => {
  return (
    <div>
      <form onSubmit={props.onSubmit}>
        <input type="text" value={props.userName} onChange={props.changed} />
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
};

Hope this will help even more: https://reactjs.org/docs/forms.html

READ ALSO
Swapping an Objects value, with a value from another object. *Javascript*

Swapping an Objects value, with a value from another object. *Javascript*

My task is to write a function that swaps the value of an element with the value at the same location within the second object

108
JPlayer Shoutcast Error - Media Url

JPlayer Shoutcast Error - Media Url

My code is working perfectly on web browsers, android, but when i try to run in iOS, appear the following error:

147
Inject console.log() in chrome inside a js file on reload

Inject console.log() in chrome inside a js file on reload

I inspected a js function and now I want to add in a consolelog() into one of the lines

165
RegExp Match returning whole word not groups

RegExp Match returning whole word not groups

I'm currently trying to validate strings in a text box with this code:

171