i'm trying to validate a basic form in reactjs which contains select dropdown box.i'm new to react and not able to figure out the correct tutorial.please suggest.
<select required className = "custom form-group" name = "workFlow"
value = {this.state.result.workflow}
required onChange = { this.handleChange} >
{
data.map((data1) => {
return <option key={data1.id}>{data1.workType}
</option>;
})
}
</select>
i am fetching data from a json file and i need to made this select field as mandatory
Using the "required" attribute with a element
you must have at least one child element
the first child element must have either an empty value attribute OR
the first child element must have no text content.
Other than that if you want to make use of event handlers then check the data that you received from the form in the onSubmit form Handler and then by making use of state display the error message or if check pass then submit the request to server.
Hope this help you out.
Related
I am new to React and I stumbled upon react-dropdown-tree-select for a specific need I had allowing users to view data in Tree format for selection in DropDown. But, I want the users to only select 1 value at a time. How can i enforce that?
There is no such property available directly in react-dropdown-tree-select. But you can listen to onChange event and reset the entire data which you have passed in data props with the updated data with only one node selected.
Check the following code.
onChange = (currentNode) => {
// keep reference of default data structure.
const updatedData = this.props.defaultData;
// find node related to currentData in your tree and set checked property
this.setState({data : updatedData });
}
render = () => {
return (
<DropdownTreeSelect
data={this.state.data}
onChange={this.onChange}
/>
);
}
This will basically stop the user from selecting multiple options instead of disabling remainig item you are unselecting the previously selected items.
If you just want one element selected at a time you can use mode="radioSelect"
I have a form, its a pickup/address form that can have multiple pickups.
Im having trouble figuring out how to get the event.target.name of the input selected to update my state correctly.
In this case, the input names are :pickups[ 0 ].pickup_datepickups[ 1 ].pickup_date
<FieldArray name="pickups" component={this.renderpickups} />
This has a button, "add pickup" that adds another address field group ( date,city,state, etc) using the documentation of fields.push..
Everytime a new pickup is added,I call a method that re-initalizes Materialize.
How do I get the event.target.name??
initializeMaterialCss(){
let pickupdate = document.querySelectorAll(".loadPickup");
let pickupdateInstance = M.Datepicker.init(pickupdate, {
onSelect: this.handleDate,
autoClose: true
});
}
I'm using the below on the Field, and then in the materialize callback, I update redux-form date property(redux-form change method) with the parameters from this react state, and the date value I get from materialize, but it feels hacky.
If there's a better more standard way, please enlighten me.
onFocus={event => this.setState({ focused: event.target.name })}
For the past days i've been searching for a way to get the value of my custom input component in the parameters of the create/edit component.
I created the component following Material UI's example in this link
The component is rendered in the application but i can't get the value of the input. Here's how I add the custom input
<Create><SimpleForm>
...
<CustomAutocompleteInput label="Main Subject" suggestions={subjectSuggestions} source="mainSubject"/>
...
</SimpleForm></Create>
Can anyone help me?
you can set a reference to the dom node
<CustomAutocompleteInput
ref={node => {this.input = node;}}
label="Main Subject"
suggestions={subjectSuggestions}
source="mainSubject"
/>
...and then access the value by
let { value } = this.input
//or
let value = this.input.value
I have a parent component in React that holds the state of the application (I'm building a filterable table). In the state I have a the filters gathered by some inputs, the state looks like this filters: [{"filter1": "value1"}, {"filter2": "value2"}, { }, { }, ...]. The filters inputs are build in a child component FilterBar that receives the filters array as a propertie <FilterBar filters={this.state.filters}/>.
So when the user writes something in the input field it updates the state of the filters (parent) according to the field name and the new input value. So far everything works as I expected. But now I want to implement a button to clean the filters, so when the user click on it the state of the filters become empty (" " string for each filter value). I success on it, when I click the button it setState as I expected, and the table is updated as I wanted. But I'm doing some mistake, the input fields receive the new filters array properties but it doesn't clean the input text (so if I had a word or letter in the input text, it still there after the rerender, and I want the input empty as the state).
Here is the parent function to clean the filters (and I realize that it works as expected):
cleanFilters() {
let filters = this.state.filters.slice();
let f;
for (f in filters) {
filters[f]['value']="";
}
this.setState({filters: filters}, function(){this.updateData();});
}
And here is the function that renders the text inputs on the FilterBar component:
renderFilterInputs() {
var filters = [];
for (let i=0; i < this.props.totalFilters; i++) {
filters.push(<td key={i}><input type='text' className="form-control" defaultValue={this.props.filtersApplied[i].value} onChange={(evt) => this.handleFilterChange(evt, i)} /></td>);
}
return filters;
}
render() {
return (
<tr key="0" className="filters-bar">
{this.renderFilterInputs()}
</tr>
);
}
I don't understand why the text input still save the text when I click the button because it rerenders again and the filter state is empty so the defaultValue of that inputs should be ("") empty. Thanks you
Because you are using defaultValue not value means uncontrolled component. Default value will assign the initial value (default value) to input element only, it will not update the value.
Solution:
Since you are using onChange function with input element and updating the parent state also, so use controlled input field, use value property instead of defaultValue.
value = {this.props.filtersApplied[i].value}
Hi I am using React 14 and writing it in ES6. I am using formsy-material-ui for form validations. There is a scenario where I want to clear the value of text field on click of a button.
I tried the following code
<FormsyText
name="email"
ref="email"
validations="isEmail"
validationError="Invalid Email"
hintText="Email"
value={this.state.emailValue}
/>
And on click of the button, I am executing the following line of code
this.setState({emailValue : ''});
But the text field is not getting cleared.
How to clear it.
Pls help.
So, if you were using a controlled input (maybe using directly the TextField from Material-ui) - your code would be right, however the FormsyText component handle it's value internally.
If you pass a value or defaultValue it'll just be used when it's rendered, you can check it here.
I only see one way to clear the value now, in an imperative style.
this.refs.email.setState({ value: "" })
Note: I suggest you to change the way you're using the ref. Using refs with a string is deprecated and probably will be removed in the future. Instead you should pass a function that's gonna receive that component. https://facebook.github.io/react/docs/more-about-refs.html
Example:
<FormsyText
name="email"
ref={(node) => this._emailText = node}
validations="isEmail"
validationError="Invalid Email"
hintText="Email"
value={this.state.emailValue}
/>
//And to clear it
this._emailText.setState({ value: "" })
Try reset field after setState:
this.setState({emailValue : ''});
this.refs.email.reset()
Also you can reset all form.
this.refs.form.reset()
const formRefdeposit = useRef(null);
<Formsy
onValidSubmit={handleSubmit}
onValid={enableButton}
onInvalid={disableButton}
ref={formRef}
>
....Form Fields
</Formsy>
if you have class in your js file then use
this.formRef.current.reset();
if without class then use
formRef.current.reset();