Forms are some elements that are created in a webpage to let the user input something for the server side to handle.
Consider the code below:
class Fourth extends Component {
render() {
return (
);
}
}
export default Fourth;
Here in this code:
Handling forms with state:
class Fourth extends Component {
constructor() {
super();
this.state = { name: '' };
}
render() {
return (
);
}
}
export default Fourth;
We can create a state based textbox in react making it able to be handled for any change in its input.
Consider the code below:
class Fourth extends Component {
constructor() {
super();
this.state = { username: '' };
}
changeHandler = (event) => {
this.setState({username: event.target.value});
}
render() {
return (
);
}
}
export default Fourth;
Handling multiple textboxes:
Multiple textboxes can simply be created having different names and then those names can be used as a reference to update the entire set of keys for the state.
Consider the code below:
class Fourth extends Component {
constructor() {
super();
this.state = {
username: '',
age: null,
};
}
changeHandler = (event) => {
let nm = event.target.name;
let vl = event.target.value;
this.setState({[nm]: vl});
}
render() {
return (
);
}
}
export default Fourth;
Handling validations in textboxes:
Validations can be made using different JavaScript functions placed inside of some conditional operators.
Consider the code below:
class Fourth extends Component {
constructor() {
super();
this.state = {
age: null
};
}
myChangeHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
if (nam === "age") {
if (!Number(val)) {
alert("Your age must be a number");
}
}
this.setState({age: event.target.value});
}
render() {
return (
);
}
}
export default Fourth;
Textarea is a type of textbox that is used to let the user write bigger texts. Very similar to the textboxes, textareas can also be handled in React.
Consider the code below:
class Fourth extends Component {
constructor() {
super();
this.state = {
description: ''
};
}
changeHandler = (event) => {
this.setState({description: event.target.value});
}
render() {
return (
);
}
}
export default Fourth;
Dropdown is a kind of list that hides many options inside. React lets a programmer handle a dropdown very efficiently.
Consider the code below:
class Fourth extends Component {
constructor() {
super();
this.state = {
hobby: ''
};
}
changeHandler = (event) => {
this.setState({hobby: event.target.value});
}
render() {
return (
);
}
}
export default Fourth;
Form submission is often based on some button events. We simply create a button and React uses the event associated with that button to do the desired task.
Consider the code below:
class Fourth extends Component {
constructor() {
super();
this.state = { name: '' };
}
submitHandler = (event) => {
alert(this.state.name);
event.preventDefault();
}
changeHandler = (event) => {
this.setState({name: event.target.value});
}
render() {
return (
);
}
}
export default Fourth;