Jpark9061
Jpark9061

Reputation: 1080

How to make an editable prefixed value in a React input box?

Any suggestions on how to make an editable input box with a pre-set value? For example, if this is the input box:

http://localhost:3000/

the user can click on this box and start editing on top of it

http://localhost:3000/sendAPI

or change the pre-set value

http://localhost:8080/sendAPI

But overall, when the app loads, http://localhost:3000/ is the initial value set, and when the user clicks on the input box, the value attribute will change to whatever is in the input box. Thank you!

Upvotes: 2

Views: 4639

Answers (2)

Atlow
Atlow

Reputation: 83

simply use the variable containig the pre-set value and connect it to the input's value and onChange event.

import React, { useState } from 'react';

function Example() {
  const [url, setUrl] = useState("http://localhost:3000");

  return (
    <div>
      <input type="text" value={url} onChange={(e) => setUtl(e.target.value)} />
    </div>
  );
}

Upvotes: 3

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

Check the below solution please . Initially value will be set to "http://localhost:3000" . Once you start change , the value will be keep updating.

class App extends Component {
  constructor() {
    super();
    this.state = {
      inputValue: 'http://localhost:3000'
    };
    this.handleChange = this.handleChange.bind(this);
  }

   handleChange(e){
    console.log(e.target.value);
    this.setState({inputValue: e.target.value});
  }

  render() {
    return (
      <div>
        <input type="text" value={this.state.inputValue} onChange={this.handleChange} />
      </div>
    );
  }
}

Upvotes: 0

Related Questions