-
-
Notifications
You must be signed in to change notification settings - Fork 2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Using the react-hook-form in class component #22
Comments
Hi @sboopal , Reason for you to getting the error. React Hook Form using React Hook which required to have version 16.8.
The benefit of React Hook is to let you use state and other React features without writing a class, but at the same time it won't work with Class component, hence React Hook Form will not work with Class component. From React documentation:
you can refer examples to get a quick start: https://github.com/bluebill1049/react-hook-form/tree/master/examples |
hey @sboopal , how did you go with functional component instead of class component? let me know if you need some help. |
Nope i havent. I am new to ReactJS. If you could point me in some direction
that would be great.
This is my code for my page. basically, i have four select components and i
need to warn the user when he presses the submit button if something is not
filled.
Thanks
Boopal
On Thu, May 2, 2019 at 12:00 AM Bill (罗贝尔) ***@***.***> wrote:
hey @sboopal <https://github.com/sboopal> , how did you go with
functional component instead of class component? let me know if you need
some help.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#22 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AII2DY4Q2RANHIOO5BKEGS3PTJYO5ANCNFSM4HJPLLQA>
.
/* eslint-disable*/
import React, { Component } from 'react';
import 'materialize-css/dist/js/materialize.min.js'
import 'materialize-css/dist/css/materialize.min.css'
import M from "materialize-css";
import moment from 'moment';
const vendorNodes = [
{
id:1,
name: 'Bay',
nodeNames: ['TDMAR', 'HBCGCD','HSBCRD'],
storeType:['Online']
},
{
id:2,
name: 'Saks',
nodeNames: ['CAPEMV', 'CSMLNK','FEPTKM','HSBCRD','PTAHUE','SMTCLX','TOKNEX','VTPDCR'],
storeType:['Physical']
},
{
id:3,
name: 'LT',
nodeNames: ['PTACRD', 'LNTGCD','HSBCRD','FEPTKM','SMTCLX','TOKNEX','VTPDCR','INCISO'],
storeType:['Online','Physical']
}
]
class BannerReport extends Component {
state = {
selectedBanner : 'Bay',
selectedStoreType:'',
selectedVendor:'',
selectedTranStatus:'',
startDate:'',
startTime:'',
endDate:'',
endTime:'',
outputType:'',
data:[],
checked:'one',
errors: {
selectedBanner : 'false',
selectedStoreType:'false',
selectedVendor:'false',
selectedTranStatus:'false',
startDate:'false',
startTime:'false',
endDate:'false',
endTime:'false',
},
valid : ''
}
componentDidMount() {
//console.log(this.state.data);
M.AutoInit();
var context = this;
var elems = document.querySelectorAll(".startDateset");
M.Datepicker.init(elems, {
onSelect: function(date) {
let errors = context.state.errors;
errors['startDate'] = (date instanceof Date) ? 'true': 'false';
context.setState({ errors, startDate: moment(date).format('YYYY-MM-DD') });
console.log(context.state.errors);
},
autoClose: true
});
var elems1 = document.querySelectorAll(".endDateset");
M.Datepicker.init(elems1, {
onSelect: function(date) {
let errors = context.state.errors;
errors['endDate'] = (date instanceof Date) ? 'true': 'false';
context.setState({ errors, endDate: moment(date).format('YYYY-MM-DD') });
},
autoClose: true
});
}
handleChange = (e) => {
const { id, value } = e.target;
let errors = this.state.errors;
errors[id] = value.length > 0 ? 'true': 'false';
if((e.target.id).includes('Time')){
this.setState({errors, [id] : moment(value,'hh:mm A').format('HH:mm:ss') })
}else{
this.setState({errors, [id] : value })
}
console.log(this.state.errors);
}
handleOnSubmit = (e) => {
e.preventDefault();
if(this.validateForm(this.state.errors)){
let URL = '/api/getCount';
if(this.state.checked === 'two'){
URL = '/api/getTranDetails';
}
fetch(URL,{
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(this.state)
})
.then((res) => {
return res.json();
})
.then((results) => {
this.setState({ data: results.data });
console.log(this.state.data);
});
}else{
console.log('invalid form');
}
}
handleRadioButtonChange = (e) => {
this.setState({checked:e.target.id});
}
validateForm = (errors) => {
let valid = true;
Object.values(errors).forEach(
// if we have an error string set valid to false
(val) => val === 'false' && (valid = false)
);
this.setState({valid})
return valid;
}
render(){
const {valid} = this.state;
const getVendor = () => {
const nodes = vendorNodes.filter((vendorNode) => vendorNode.name === this.state.selectedBanner)[0];
return(
<select id="selectedVendor" className="browser-default" onChange={this.handleChange}>
<option value="" disabled selected>Select</option>
{nodes.nodeNames.map(m => <option value={m}>{m}</option>)}
</select>
)
}
const getStoreType = () => {
const nodes = vendorNodes.filter((vendorNode) => vendorNode.name === this.state.selectedBanner)[0];
return(
<select id="selectedStoreType" className="browser-default" onChange={this.handleChange}>
<option value="" disabled selected>Select</option>
{nodes.storeType.map(m => <option value={m}>{m}</option>)}
</select>
)
}
const getTableData = () => {
const JsonTable = require('ts-react-json-table');
return(
this.state.data.length ? (
<JsonTable className="table striped bordered" rows={ this.state.data } />
): (
null
)
)
}
return(
<div className="container">
<div className="row">
<form className="col s12" onSubmit={this.handleOnSubmit}>
<div className="row">
<h6 className="col s12 m2">Banner</h6>
<div className="input-field col s12 m3">
<select
name="bannerDropDown"
id="selectedBanner"
className="browser-default"
onChange={this.handleChange} >
<option value="" disabled selected>Select</option>
{vendorNodes.map((vendorNode) => <option key={vendorNode.id} >{vendorNode.name}</option> )}
</select>
{/* <label>Banner</label> */}
</div>
<h6 className="col s12 m2 offset-m1">Store Type</h6>
<div className="input-field col s12 m3">
{getStoreType()}
</div>
</div>
<div className="row">
<h6 className="col s12 m2">Vendor</h6>
<div className="input-field col s12 m3">
{getVendor()}
</div>
<h6 className="col s12 m2 offset-m1">Tran Status</h6>
<div className="input-field col s12 m3">
<select id="selectedTranStatus" className="browser-default" onChange={this.handleChange}>
<option value="" disabled selected>Select</option>
<option value="0">Approved</option>
<option value="1">Declined</option>
<option value="10">Timeout</option>
<option value="2">Onhold</option>
</select>
{/* <label>Status</label> */}
</div>
</div>
<div className="row">
<h6 className="col s12 m2">Start Date</h6>
<div className="input-field col s6 m3">
<input id="startDate" type="text" className="datepicker startDateset" />
</div>
<div className="input-field col s6 m3">
<input id="startTime" type="text" className="timepicker" onSelect={this.handleChange} />
</div>
</div>
<div className="row">
<h6 className="col s12 m2">End Date</h6>
<div className="input-field col s6 m3">
<input id="endDate" type="text" className="datepicker endDateset" />
</div>
<div className="input-field col s6 m3">
<input id="endTime" type="text" className="timepicker" onSelect={this.handleChange} />
</div>
</div>
<div className="row">
<h6 className="col s12 m2">Output Type</h6>
<p className="input-field col s6 m3" >
<label>
<input name="group1" id='one' checked={this.state.checked === 'one'}
onChange={this.handleRadioButtonChange}
className='with-gap' type="radio" />
<span>Count</span>
</label>
</p>
<p className="input-field col s6 m3" >
<label>
<input name="group1" id='two' checked={this.state.checked === 'two'}
onChange={this.handleRadioButtonChange}
className='with-gap' type="radio" />
<span>Transaction Details</span>
</label>
</p>
</div>
<button className="btn waves-effect waves-light">Submit
<i className="material-icons right">send</i>
</button>
</form>
</div>
{valid === false &&
<span className='center red-text'>Please fill the form and submit</span>}
<br />
{getTableData()}
</div>
);
}
}
export default BannerReport;
|
here is a quick sandbox for validating couple selections. (functional component) https://codesandbox.io/s/qk47j6854j hope you find this useful cheers |
thanks for the quick response. My componenet is class component. Do you
suggest to create a functional component and add taht in the class?
Thanks
Boopal
…On Fri, May 3, 2019 at 6:40 PM Bill (罗贝尔) ***@***.***> wrote:
here is a quick sandbox for validating couple selections. (functional
component)
https://codesandbox.io/s/qk47j6854j
hope you find this useful
cheers
bill
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#22 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AII2DY7L7HVDPQ6FYDR7P53PTTEQPANCNFSM4HJPLLQA>
.
|
Firstly, make sure you check your If so, then it is better to convert to functional component and try out If you want more examples, which can be found here: API has been fully documented here too: let me know if these are helpful. cheers |
Hey @sboopal, is there anything I can help more? otherwise, I may have to close this issue. |
Yep thanks
On Tue, May 7, 2019 at 7:15 AM Bill (罗贝尔) ***@***.***> wrote:
Closed #22 <#22>.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#22 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AII2DYZWBLZZPQB3EBV4I53PUFXFNANCNFSM4HJPLLQA>
.
--
Thanks
Boopal
|
hope you get the chance to use react hook form in the future :) |
How do i add the hook into a class component? the current examples show only to add it to function component?
Getting this error when I try to add it in a function
Uncaught Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
at invariant (http://localhost:3000/bundle.js:45863:15)
at Object.throwInvalidHookError (http://localhost:3000/bundle.js:58675:3)
at useRef (http://localhost:3000/bundle.js:70887:21)
at useForm (http://localhost:3000/bundle.js:67453:75)
at BannerReport.render (http://localhost:3000/bundle.js:82491:85)
at finishClassComponent (http://localhost:3000/bundle.js:60549:31)
at updateClassComponent (http://localhost:3000/bundle.js:60504:24)
at beginWork (http://localhost:3000/bundle.js:61452:16)
at performUnitOfWork (http://localhost:3000/bundle.js:65120:12)
at workLoop (http://localhost:3000/bundle.js:65160:24)
The text was updated successfully, but these errors were encountered: