Blank
Blank

Reputation: 443

Reading two input strings and concatinating them

I am writing a react component that reads the users first name and second name and then generates random usernames for them.

class App extends Component {
  render() {
    return (
      <div className="App">
        First name:<br/>
        <input type="text"></input><br/>
        Last name:<br/>
        <input type="text"></input><br/>
        <button type="button">make a username</button>
        <p>{generateUN('fname','lname')}</p>
      </div>
    );
  }
}

How can I pass the values from the input fields to the function after the button is triggered?

Upvotes: 1

Views: 64

Answers (2)

AngelSalazar
AngelSalazar

Reputation: 3113

you can use state to create the username, here is a small example

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fn : '',
      ln : ''
    }
  }

  // makeUsername creates
  // the username based on the fn and ln
  // provided in the inputs
  makeUsername () {
    const {fn, ln} = this.state;
    // if either fn or ln is not provided, do nothing
    if (!fn || !ln) return;

    this.setState({
      username : `${fn.trim()}@${ln.trim()}`
    });
  }

  // createChangeHandleris a curried function to specify
  // which piece of state will be modifed
  createChangeHandler (stateKeyToUpdate) {
    return (e) => {
      this.setState({
        [stateKeyToUpdate] : e.target.value
      });
    }
  }

  render () {
    // conditional render
    // if the username exists 
    // then  render the div
    /*{
        username &&
        <div>Your username is {username}</div>

    }*/
    const {fn, ln, username} = this.state;
    return (
      <div>
        <input 
          value={fn}  
          onChange={this.createChangeHandler('fn')}
          />
        <input 
          value={ln}
          onChange={this.createChangeHandler('ln')}
          />
         <button onClick={this.makeUsername.bind(this)}>
           create username
         </button>

         {
           username &&
           <div>Your username is {username}</div>
         }
      </div>
    );
  }
}

ReactDOM.render(<App />, document.querySelector('#root'))

And a demo

Upvotes: 4

Richard
Richard

Reputation: 1038

You can use an inline onClick or an eventlistener

 First name:<br/>
    <input type="text" id='btn1'></input><br/>
    Last name:<br/>
    <input type="text" id='btn2'></input><br/>
 <button id='mybutton' onClick="myRandomFunction(getElementById(btn1).value,getElementById(btn2).value)" >make a username</button>

Or

<script>
getElementById('mybutton').addEventListener("click", myRandomFunction(getElementById(btn1).value,getElementById(btn2).value);
</script>

Upvotes: -1

Related Questions