Overwrite initial value from redux-form - reactjs

I am initializing values in Field using initialValues. Although I would like to overwrite one of the Field with another defaul value.
Is this possible? I was trying with defaultValue etc but I doesnt work.
This is the part of code I want to change:
<Field
type="text"
name={`${some}.url`}
component={renderField}
label="URL"
defaultValue={some.url + ':' + some.port}
/>
Its initialized with url, but I would like to change it to url:port

Before passing initialValues prop down to your redux-form component, you can modify it.
Something like that:
const mapStateToProps = state => ({
// Here's how to set a default value and overwrite the API initial data.
// Let's say your form is editing an User.
// And if the User, returned by the API, doesn't have a name,
// then we set a default value.
initialValues: {...state.user, name: state.user.name || 'Default name'}
)}
// `connect` is part of `react-redux`.
// If you don't use `react-redux`, then just modify the `initialValues`
// before passing it down to the form.
export default connect(mapStateToProps)(reduxForm({
form: 'formName',
})(Component))

Not sure what and how you generate or update your url and port variables. But something like this should work. If you can share more details, I can adapt the answer.
private url: string = `${some}.url`;
private port: string = `${some}.port`;
<Field
type="text"
name={this.url}
component={renderField}
label="URL"
defaultValue={this.url + ':' + this.port}
updateDefaultValue={(url, port) => {this.url = url; this.port = port}}
/>
in your Field component
this.props.updateDefaultValue("xxx","yyy");
Hope this helps

Related

Access string of selected place in StandaloneSearchBox in react-google-maps/api

I'm wondering how I can access the actual value in a <StandaloneSearchBox ..> component after the user selected it from the autocomplete dropdown menu. I basically want to make it a controlled component.
I tried getPlaces() but that does not give me the actual value visible on the page but rather a bunch of structured data.
Take the example from the official docs (https://react-google-maps-api-docs.netlify.app/#standalonesearchbox), I basically want to do something like:
...
const [inputFieldValue, setInputFieldValue] = useState ("")
const onPlacesChanged = () => {
...
const value = ... // 1. access value
setInputFieldValue (value) // 2. store in state
}
...
<input
type="text"
placeholder="Customized your placeholder"
style={{...}}
value= {inputFieldValue}
/>
...

Getting Default value in React Hook?

I have an input field with a default value
<input type="text" name="default" value="one" />
I'm using react hook to use state
const [def, setdef] = useState({Default:""})
what I want is to set the input default value one to the state
Desired Output
setdef({...def, Default:"one"})
how can I achieve this? I know about the onChange function but I don't think it will work.
any better suggestion is appreciated. thanks in advance
I assume that you need to create a hook with a default string, like this:
const Component = () => {
const [string, setString] = useState("hello") // <-- this is the default value of the input
// Set the hook value into the content of the input
const handleChange = (event) => {
setString(event.target.value);
}
return <input value={string} onChange={handleChange} />
}
The input's content would be "hello" by default, but the user can change it. Delete the onChange event to make it read-only.
(mi comentario estaba en español, perdón por la mala traducción no soy bueno en el ingles)
I think this is what you need
When using hooks one can specify what value it will have by default like this:
const [def, setdef] = useState("one")
by doing what is above you will get the value that I add in quotes when occupying -> def.
<input type="text" name="default" value={def} />
the input will obtain an initial value that will be "one"
and if you want to modify its value you will only have to do this:
setdef("new value")

React Dynamic Form with React State

So i need to create a form in react with dynamics fields , these fields are elements in an Array ,
so i have to create an Object (which is a state using useState hook) from the Form , and the fields should be the properties of this object , my code :
const [object, setObject] = useState({})
const onChange = e => {
setObject({...object,[e.target.name]:e.target.value})
}
const properties = ["to","placeFrom","placeTo","from","date"]
{properties.length !== 0 &&
<form>
{properties.map(property =>
<input type="text" class="form-control" name={property} value={object.property} onChange={onChange}/>
)}
</form>
}
The Object in state should be like this :
{
to: value,
placeFrom: value,
placeTo: value,
from: value,
date: value,
}
the problem is in the value attribute in the input , i couldn't make it dynamic too.
Thanks in advance!
The problem is how you are accessing the object state when setting the value for the <input/>.
By doing object.property, you are asking javascript to provide the value associated with the property key on the object. That would return a value if your state object was of the form:
{
property: 'some-value'
}
In this case there is no key in your state called property and this is not the intended behavour.
To access the object dynamically with the variable property, you can do this: object[property].
Thus your input would look like
<input type="text" class="form-control" name={property} value={object[property]} onChange={onChange}/>
I might also suggestion that instead of calling your state object, you could provide a more descriptive name like formValueState or something like that.
Good luck!

How to parse untouched fields in react-final-form

I have an input for an amount in react-final-form. If it's not filled, I need to set its form value to zero. I can't pass an initial value to it as if it hasn't been filled by the user, the input itself should stay empty.
In react-final-form docs there's a parse function. But it works only if the field has been touched (filled and then cleared by the user). Is there any way to parse untouched fields and set them to zero in form values, without updating the input?
Here is my code:
<Field
name="amount"
component={CurrencyInput}
parse={value => (value ? value : 0)}
/>
And here is the link to my codesandbox.
if by doing this what you are trying to accomplish is that the object displayed in the <pre> has a default value of zero when the input is empty you could use a state variable and inside the parse keep updating its value
const [amount, setAmount] = useState(0);
const onInputChange = e => {
e === "" || e === undefined ? setAmount(0) : setAmount(e);
};
and in the Field tag
<Field
name="amount"
component={CurrencyInput}
parse={value => onInputChange(value)}
defaultValue={amount}
/>
check the codesandbox here:
https://codesandbox.io/s/react-final-form-wreact-number-format-and-parse-22q3n
Hope this Resolves the issue

as am not getting what is the functionality of below code

Can someone explain me below function line by line
handleChange(e) {
let fields = this.state.fields;
fields[e.target.name] = e.target.value;
this.setState({
fields
});
as my understanding
we are creating a variable fields and storing the present state of fields in the variable because we cant mute the state.
i don't have idea about fields[e.target.name] = e.target.value;
updating the fields
can someone explain me the above function line by line?
fields[e.target.name] this syntax is also used to access the Object Properties.
var obj = {name:'abc', color:'red'}
console.log(obj.name) // this print 'abc'
console.log(obj['name']) // also print 'abc'
with obj['xxx'] syntax you can dynamically read and set properties to the object.
reference https://www.w3schools.com/js/js_objects.asp
So in your problem fields variable take existing fields object from the local state. And in each event it create new property with that event target name and add that event target value as that new property value. if that property name already exist within the fields object then it only modified the value of that property.
So as in your list,
is correct. With let fields = this.state.fields; it get previously stored values into the fields variable. without losing previous data
this is what I explained above
your answer is correct. update the state with old and new values
This code let's you dynamically change the value of a field in your component state by using object notation. object[]
By using fields[event.target.name] you're going to look for a field in your component state that matches the name of the element that's causing the event to occur. Then it looks like you're updating the value for that field with event.target.value
Why this is useful
Let's say you have a component where you want to retrieve multiple inputs from a user. Without object notation, you might end up writing very repetitive code like writing a different event handler for each input in order to determine what field to update in your component state:
BAD:
handleOnChange1 = (event) => (this.setState({userName: event.target.value}))
handleOnChange2 = (event) => (this.setState({lastName: event.target.value}))
However, by naming your elements and coordinating them with a matching field in your component state, you won't have to worry about writing additional event handlers as long as you use object notaton.
GOOD:
class UserForm extends React.Component{
state = {
firstName: "",
lastName: ""
}
handleOnChange = (event) => {
this.setState({
[event.target.name]: event.target.value
})
}
render(){
return(
<div>
<input name="firstName" value={this.state.firstName} onChange={this.handleOnChange}/>
<input name="lastName" value={this.state.lastName} onChange={this.handleOnChange}/>
</div>
)
}
}

Resources