form hooks code example
Example 1: react-hook-form material-ui
import React from "react";
import { useForm, Controller } from "react-hook-form";
import Select from "react-select";
import Input from "@material-ui/core/Input";
import { Input as InputField } from "antd";
export default function App() {
const { control, handleSubmit } = useForm();
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller as={Input} name="HelloWorld" control={control} defaultValue="" />
<Controller as={InputField} name="AntdInput" control={control} defaultValue="" />
<Controller
as={Select}
name="reactSelect"
control={control}
onChange={([selected]) => {
return { value: selected };
}}
defaultValue={{}}
/>
<input type="submit" />
</form>
);
}
Example 2: React Hook Form
import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from "react-redux";
import useForm from 'react-hook-form';
function SampleForm() {
const { register, handleSubmit } = useForm();
const onSubmit = data => {
alert(JSON.stringify(data));
};
return (
<div className="App">
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="firstName">First Name</label>
<input name="firstName" placeholder="bill" ref={register} />
</div>
<div>
<label htmlFor="lastName">Last Name</label>
<input name="lastName" placeholder="luo" ref={register} />
</div>
<div>
<label htmlFor="email">Email</label>
<input name="email" placeholder="[email protected]" type="email" ref={register} />
</div>
<button type="submit">Submit</button>
</form>
</div>
);
}
class Sample extends Component {
constructor(props) {
super(props);
}
render() {
return <SampleForm />;
}
}
export default connect()(Sample);
const rootElement = document.getElementById('root');
ReactDOM.render(<Sample />, rootElement);