0

I am new to React trying to write a very simple project that fetches input of both text boxes and when button is clicked, the 'data' in text boxes is printed on paragraph.

How do I fetch text's in input text boxes when button is clicked?

class Input extends Component {
    state = { 
        tagged: false,
        message: '', 
    }

    handleClick(e) {
        this.setState({tagged: true});
        e.preventDefault();
        console.log('The link was clicked.');
    }

    render() {                                                
        return (
            <div id="id" style={divStyle}>
                <p> hello </p>
                <input
                    style = {textStyle}
                    placeholder="[email protected]" 
                    type="text">
                </input>

                <input
                    style = {textStyle}
                    placeholder="tag" 
                    type="text">
                </input>
                <button
                    onClick={(e) => this.handleClick(e)}
                    style={buttonStyle}>
                    {this.state.tagged ? 'Tagged' : 'Tag ' } 
                </button>

                <p>
                    {this.state.tagged ? 'Clicked' : 'Still' }
                </p>
            </div>    
        )
    }
}

2 Answers 2

1

You can add onChange event handler in each input.

class Input extends Component {
    state = { 
        tagged: false,
        message: '',
        input1: '',
        input2: '',
    }

    handleClick(e) {
        // access input values in the state
        console.log(this.state) // {tagged: true, input1: 'text', input2: 'text2'}
        this.setState({tagged: true});
        e.preventDefault();
        console.log('The link was clicked.');
    }

    handleInputChange = (e, name) => {
      this.setState({
       [name]: e.target.value
     })
    }

    render() {                                                
        return (
            <div id="id" style={divStyle}>
                <p> hello </p>
                <input
                    style = {textStyle}
                    placeholder="[email protected]" 
                    type="text"
                    onChange={(e) => this.handleInputChange(e, 'input1')}
                >
                </input>

                <input
                    style = {textStyle}
                    placeholder="tag" 
                    type="text"
                   onChange={(e) => this.handleInputChange(e, 'input2')}
               >
                </input>
                <button
                    onClick={(e) => this.handleClick(e)}
                    style={buttonStyle}>
                    {this.state.tagged ? 'Tagged' : 'Tag ' } 
                </button>

                <p>
                    {this.state.tagged ? 'Clicked' : 'Still' }
                </p>
            </div>    
        )
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

There are two different ways of working with react inputs - you can either make them controlled or uncontrolled. When you say fetch text from inputs, this is called uncontrolled components and means that form data is handled by the DOM itself and not by react.

This is achieved by using ref and literally getting a reference to your input and fetching its value when you need it. you can read more about this approach in react docs.

According to react docs, it is recommended using controlled components

In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component.

This means that you don’t use references to the inputs and instead handle changes of your inputs with an event handler and update state with the new values that the user has entered into the input fields. According to react docs here is how react handles form with controlled components:

the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.

In your case you can do this if you choose controlled inputs:

class ControlledInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tagged: false,
      firstInput: '',
      secondInput: ''
    }
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }
  handleClick(e) {
    this.setState({ tagged: true });
    e.preventDefault();
    console.log('The link was clicked.');
  }

  render() {
    const { firstInput, secondInput, tagged } = this.state;
    return (
      <div id="id">
        {tagged && <p>{firstInput} {secondInput}</p> }
        <input 
          value={firstInput} 
          name="firstInput"
          onChange={this.handleChange} 
          type="text" />
        <input 
          value={secondInput} 
          name="secondInput"
          onChange={this.handleChange}
          type="text" />
        <button onClick={(e) => this.handleClick(e)}>
          {tagged ? 'Tagged' : 'Tag '}
        </button>
      </div>
    )
  }
}

Here you put the inputs' values on state and update state when the user writes something in your inputs. If you however want to use uncontrolled components you can do it this way:

class UncontrolledInput extends React.Component {
  state = {
    tagged: false,
    message: '',
  }

  handleClick(e) {
    e.preventDefault();
    const messageFromInputs = `${this.firstInput.value} ${this.secondInput.value}`;
    this.setState({ tagged: true, message: messageFromInputs });   
  }

  render() {
    return (
      <div id="id">
        <p>{this.state.message}</p>
        <input ref={(input) => this.firstInput = input} type="text" />
        <input ref={(input) => this.secondInput = input} type="text" />
        <button onClick={(e) => this.handleClick(e)}>
          {this.state.tagged ? 'Tagged' : 'Tag '}
        </button>
        <p>
          {this.state.tagged ? 'Clicked' : 'Still'}
        </p>
      </div>
    )
  }    
}

Here you will actually fetch values from your inputs when the button is clicked.

I made a working example with both ways on codesandbox.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.