Can't seem to use null as a default value?
I have a custom input component that declares:
Component.propTypes = {
value: PropTypes.number
};
Because mobx-react-form defaults the value to an empty string, I'm getting proptype errors in the console. So, I figured I could override the default value and set it to null, but an empty string still seems to be getting passed in. I tried default: null, initial: null, and value: null, but nothing worked.
I've tried looking for documentation about default values, but I couldn't seem to find much of anything. Sorry for asking questions in the issue tracker 😄 .
At the risk of more configuration boilerplate, do you think it would it be best for users to provide their own default values instead of assuming an empty string?
Hi @rzane
How can you render the null value into an input?
Can you provide the complete code of the form and the component?
So in the case of <input />, it can't be null. But, in the case of a custom input component, null is actually very common I think. <ReactSelect />, for example, can be null.
Input components really just need to follow the contract of value/onChange. They might invoke onChange with an array or an object. You wouldn't want the initial value of an input that calls onChange with an object to take an empty string as an initial value. Therefore, null makes the most sense.
This is a contrived example, but imagine you have a custom input component that knows how to manage objects with a certain structure.
class DistanceInput extends Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.shape({
distance: PropTypes.number.isRequired
}),
};
handleChange = (event) => {
const { value } = event.target;
if (value) {
this.props.onChange({
distance: parseInt(event.target.value, 10)
});
} else {
this.props.onChange(null);
}
}
render () {
return (
<input
type='number'
value={this.props.value ? this.props.value.distance : 999}
onChange={this.handleChange}
/>
);
}
}
Create the form:
class FormState extends MobxReactForm {}
// normally, this would be passed as a prop, but for time saving...
const form = new FormState({
fields: [{
name: 'distance',
label: 'Distance'
}]
};
class Form extends Component {
render() {
const distance = form.$('distance');
return (
<form onSubmit={form.submit}>
<DistanceInput
value={distance.value}
onChange={distance.onChange}
/>
</form>
);
}
}
This will trigger a propType error, because the distance input expects null or an object.
To answer your original question, you can set the initial values on the fields passing it to the form constructor, it will be set as value, default, and initial field props. If you want to override the default prop, you can specify it in the field object, but cannot be null.
new FormState({
fields: [{
name: 'distance',
label: 'Distance'
value: 1000, // <<< initial state
default: 50, // <<< default value
}],
});
In the code you provided, you are using a normal input, which will not accept a null value anyway.
You are trying set an object into a field which you want to be int.
In the handleChange implementation, you are passing an object with an additional distance prop, just pass the int value to it, the package will take care of the parsing, then also change value={this.props.value.distance} to value={this.props.value}. (each field has a computed value to be attached to the input).
Moreover, if you use value={this.props.value.distance} and then you do this.props.onChange(null), this.props.value.distance should be undefined.
The numbers will be automatically handled by the package if you provide an int value like in this demo example.
If you want to show nothing into the input, it cannot be an int, in must be a string (empty string). If you choose to show a number, it will be zero if no numbers are provided. Otherwise, handle the value as a string and afterward parse it to integer.
About submitting the form, you should change onSubmit={form.submit} to onSubmit={form.onSubmit} as submit() is not an event handler (doesn't accept the Proxy object, it accept an object with onSuccess and onError callbacks.
Check the docs about the handlers: Event Handlers Decoupling the Handlers Manual Form Submit (Actions)
Here you can find an example of my implementation of a React Select component: src/forms/Search.js src/components/SearchForm.jsx
I will try to understand how to better handle null values, because if I allow them, they will breaks some tests. It seem can not be possible right now until I find a good solution, but I think your issue is related to a different point of view for the inputs implementation which is different from the solution provided by this package.
Some discussion about null values on inputs:
https://github.com/facebook/react/issues/6996 http://stackoverflow.com/questions/17240432/insert-null-value-into-a-text-input http://stackoverflow.com/questions/36187522/react-select-with-value-null
Yes, I understand that <input /> doesn't accept null in react, but the point I'm trying to make is that custom components often do. My example did a terrible job of attempting to make that point. Basically, I'm just trying to say that often in React, input components can be more complex than <input /> tags, and therefore, it would be nice if null could be the initial value.
Is this library expecting to ALWAYS deal with strings? Take this example:
var Form = require('mobx-react-form').Form;
var form = new Form({ fields: ['ids[]'] });
form.update({ ids: [1, 2, 3] });
console.log(form.values()); // { ids: [] }
form.update({ ids: ['1', '2', '3'] });
console.log(form.values()); // { ids: [ '1', '2', '3' ] }
Numbers don't work on initialize either:
var Form = require('mobx-react-form').Form;
var form = new Form({
fields: ['ids[]'],
values: { ids: [1, 2, 3] }
});
console.log(form.values()); // { ids: [] }
As I said before, this package is able to handle numbers.
Thank you for this code example, it seems you found a bug, it's related to the fields value parsing, I will fix it asap.
About the use of custom input components, the implementation will differ for each situation. I can not know in advance how your components will be structured and how the values are treated.
The purpose of this package is to simplify the state management of generic input fields, it's up to you understand how it works, reading the docs or with my help of course, so you can use it to implement your custom components in the best possible way.
About the use of null values, I will deepen your issue and I will update the package if I found a proper solution.
It seems that another case exists when 'null' as default value can be useful. If we have a conditional input, that is rendered, for example, when a checkbox set to true.
If we change other fields on the form and keep the checkbox with false value - the initial value of the input should be null, but not an empty string.
@foxhound87 Do you have any updates about this issue maybe?
@AndrewGulidov Right now you can convert to null when the get() method is called, you can try to use Input/Output converters to achieve that.
In the future, I will provide a better mechanism to convert field data with custom logic which will be also managed with additional computed props and that could be validated in place of the value prop.
For the record, I make it work with this :
simulationDate: {
label: 'Simulation date',
placeholder: 'Simulation date'+ '..',
rules: 'required|date',
value:'',
input: value => value === '' ? null : value,
output: value => value === '' ? null : value
}
Ok, I fall again on this error of null to "", and saw my anwser 👍 Thanks me ..