Noname
Noname

Reputation: 175

Can't edit value of input element in React

I have a problem with my React project, I have an input element like below but I can't edit the text of the input. I just can edit the input text only when I delete the value attribute, but I want a default value for it.

  <div className="form-group">
       <label>Email:</label> 
       <input  
          className="form-input" 
          type="text" 
          value="[email protected]" 
          name="email">
       </input>
  </div>

Upvotes: 1

Views: 3537

Answers (4)

joy08
joy08

Reputation: 9652

Set the default value inside the state object and attach a change handler to the input to capture the changes:

Sample codesandbox: https://codesandbox.io/s/react-basic-class-component-22fl7

class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
                    inputValue: '[email protected]'
                 };
  }

  handleChange = event => {
      this.setState({ inputValue: event.target.value }, () =>
          console.log(this.state.inputValue)
      );
  };

  render() {
    return (
       <div className="form-group">
         <label>Email:</label> 
         <input  
           className="form-input" 
           type="text" 
           value={this.state.inputValue}
           onChange={this.handleChange} 
           name="email">
         </input>
       </div>
    );
  }
}

Upvotes: 0

Burak Gavas
Burak Gavas

Reputation: 1354

Here is a sample code how to use inputs in react

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

Upvotes: 0

Ramiz Wachtler
Ramiz Wachtler

Reputation: 5683

If you've an uncontrolled component, you might want to use the defaultValue property instead of value (See this reference)

Upvotes: 4

iamhuynq
iamhuynq

Reputation: 5529

You can use useRef or defaultValue

import React, { useRef, useEffect } from "react";

const input = useRef();
useEffect(() => {
    input.current.value = "[email protected]";
}, []);

<input ref={input} className="form-input" type="text" name="email" />`

Upvotes: 0

Related Questions