11 January 2020

Form input control example in react

  • Create Components folder under src folder
  • Add FormInputCTRLEXP.js file and add below Code
import React, { Component } from "react";

class FormInputCTRLEXP extends Component {
constructor(props) {
super(props);

this.state = {
fullName: ""
};
}

handleSubmitForm = e => {
alert("Full Name: " + this.state.fullName);
e.preventDefault();
};

handleChange = e => {
var value = e.target.value;
this.setState({
fullName: value
});
};

render() {
return (
<form onSubmit={this.handleSubmitForm}>
<label>
Full Name:
<input
type="text"
value={this.state.fullName}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
<p>{this.state.fullName}</p>
</form>
);
}
}
export default FormInputCTRLEXP;
  • Open index.js file and update code as below
import React from "react";
import ReactDOM from "react-dom";
import FormInputCTRLEXP from "./component/FormInputCTRLEXP";

import "./styles.css";

function App() {
return (
<div className="App">
<FormInputCTRLEXP />
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Output:


No comments:

Post a Comment