Getting Default value in React Hook? - reactjs

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")

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}
/>
...

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

Overwrite initial value from redux-form

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

how to reference the quantity value when onchange is called in JSX component

This seems like it should be simple, but I'm a little lost in the context of React. Any help would be much appreciated!
I am trying to use a quantity selector component (written by someone else), and onChange i want to reference the new value of the quantity in the callback, but when i use this.value it doesn't seem to work as shown below (i get a type error undefined in console).
Is there some other way to reference the "new" numerical value of the quantity dropdown?
<QuantitySelector value = {props.itemCartQty} onChange = {() => props.updateItemQty(props.item, this.value)}
/>
Pass the value from the onChange method like
<QuantitySelector value = {props.itemCartQty} onChange = {(value) => props.updateItemQty(props.item, value)}
/>
Here onChange by default receives the updated value returned from the QuantitySelector component and passes it on the the updateItemQty method
Not sure what is this.value in your example, my guess is selected value. if thats the case, you can pass the event and get the selected value. Can you try the following code and see if it works for you.
updateItemQty(item, event){
var val = event.target.value;
.....
}
<QuantitySelector value = {props.itemCartQty} onChange = {(event) => props.updateItemQty(props.item, event)}
/>

Resources