How to get value as string, not object - reactjs

I use react-select inside my Redux form and I want me input filled with my value option, not the entire option.
Today, my form field is {'label':'text', 'value':'a'}. What I want is just a.
Here is my code:
[...]
renderField = data => {
return (
<Select
id={`xxx_${data.name}`}
name={data.name}
options={data.options}
value={data.input.value}
getOptionValue={option => option['value']}
onChange={(value) => data.input.onChange(value)}
onBlurResetsInput={false}
/>
);
};
[...]
render() {
return (
<Field
type={"select"}
component={this.renderField}
options={[{"label":"test1", "value":"a"}, {"label":"test2", "value":"b"}, {"label":"test3", "value":"c"}]}
name={"xxx"}
/>
);
};
So, I don't want the entire option in my form, but only the value of the option.
Do you know how to do that?
Thank you
EDIT
I tried to add a normalize on my field:
normalize={(value) => value.value}
It work but now, the display is wrong...

Related

React final form - Unable to pass function to oChange prop

I have a in a form using react final form. I'm trying to pass the value of the current input to a function thats used when the field value changes. However when I type, it's taking no input.
<Field name="myField">
{({ input, meta }) => (
<div>
<TextField
type="text"
name={input.name}
value={input.value}
onChange={() =>
handleChange(input.value)
}
label="Title"
/>
</div>
)}
</Field>
I have a function handleChange above the render method. All I want to do is console the current value, and use a setState hook to update a state variable.
function handleChange(item: string) {
setTitle(item);
console.log(item);
}
What am I doing wrong?
I would personally use a useEffect to achieve this, but the issue is that once you add your own useEffect onto it, then it overrides the default action which saves the form value to the form itself.
So first you still have to do the default onChange. And you want to take the value from the input field using e.target.value.
In your example, you are passing the value of the input field into your handeChange, but becuase you arent saving the value back into the input and the form, its always going to be empty.
<Field name="myField">
{({input}) => (
<div>
<TextField
name={input.name}
value={input.value}
onChange={(e, val) => {
console.log(e.target.value);
handleChange(e.target.value)
input.onChange(e.target.value);
}}
/>
</div>
)}
</Field>

Set checkbox checked state of checkbox group programmatically in Formik

I have a checkbox group (checkboxes with the same name), that I'd like to toggle them through an external button.
The parent component will map over the data and create multiple checkboxes given the data, like so:
(options.map(
option => (
<Field
name={field.name}
value={option.value}
component={CheckBoxButton}
/>
)
)}
And the CheckBoxButton is
const CheckBoxButton = ({
value,
field,
...props
}) => {
const [activeState, setActiveState] = useState(false)
return (
<div>
<Field
type="checkbox"
{...field}
{...props}
value={value}
checked={activeState}
/>
<Button
active={activeState}
onClick={() => {
setActiveState(!activeState)
}}
>
Toggle Checkbox
</Button>
</div>
)
}
Now on submission, it seems the checked={activeState} value passed to the field seemed to be ignored, nor that it triggers onChange when changed. I have tried to use setFieldValue() but since we have multiple checkboxes with the same name, it only captures the last value. To use it means I'd have to manually structure the value array and pop/add values, which seems like an overkill.
I also tried using useRef and setting ref.current.checked manually, but at no use.
Any insights on what I might be doing wrong, or how to properly set the value programmatically?
So, I managed to get a workaround that solves the problem by wrapping the button (now a div) and checkbox within the same Label, and overriding the state within the onChange event of the field. Each field would have a unique identifier id which the label binds to using htmlFor.
While a valid workaround, it would still be nice to have a programmatic way to do so.
const CheckBoxButton = ({value,field,...props}) => {
const [activeState, setActiveState] = useState(active)
const { handleChange } = useFormikContext()
const fieldId = `${field.name}-${value}`
return (
<label htmlFor={fieldId}>
<Field
id={fieldId}
type="checkbox"
{...field}
{...props}
value={value}
onChange={(event) => {
setActiveState(!activeState)
handleChange(event)
}}
className={style.checkbox}
/>
<span active={activeState} >
Toggle Checkbox
</span>
</label>
)
}

Mutator to covert text to uppercase

I tried different ways to implement mutator to convert text to uppercase as soon as user input text in the text field. But was not yet successful. The example provided by Erick seems correct, but maybe I am missing something.
/** Converts a form value to uppercase **/
const upper = ([name], state, { changeValue }) => {
changeValue(state, name, (value) => value.toUpperCase())
}
<Form
onSubmit={onSubmit}
mutators={{
...arrayMutators,
upper
}}
render={({
handleSubmit,
mutators: { push, pop, upper }, // injected from final-form-arrays above
pristine,
reset,
submitting,
values
}) => {
return (
<form onSubmit={handleSubmit}>
<div>
<label>Company</label>
<Field name="company" component="input" onChange={(e) => upper('company')} />
</div>
</form>
)}
}
/>
It's throwing an error when calling toUpperCase on value as value is coming undefined there. Really appreciate any help!
Update: 27-Oct-2018
I have realized we can use parser too, to solve this problem:
upper = value => {
return value ? value.toUpperCase() : ''
}
<Field name="company" component="input" parse={this.upper} />
Still looking for how mutator works and what's the error in my code.
Already Tried:
Mutate state based on existing fields
How to set/change Field value from external user action 🏁 React Final Form
As I know about react-final-form you can get this data directly
I will suggest, you can use this code
onChange={(event, value) => input.onChange(value.toUpperCase())}
https://codesandbox.io/s/0x9y71nwyp

How to use custom Input with Formik in React?

I'm trying to use DatePicker within Formik. But when I click DatePicker's date its form value is not changed. Instead, I got this error:
Uncaught TypeError: e.persist is not a function
at Formik._this.handleChange (formik.es6.js:5960)
I shortify code, the code is below
const SomeComponent = () => (
<Formik
render={({
values,
handleSubmit,
handleChange,
setFieldValue
}) => {
return (
<div>
<form onSubmit={handleSubmit}>
<DatePicker
name={'joinedAt'}
value={values['joinedAt']}
onChange={handleChange}
/>
</form>
</div>
)
}}
/>
)
I googled few documents, https://github.com/jaredpalmer/formik/issues/187 and https://github.com/jaredpalmer/formik/issues/86
So I tried like below, but it's not working.
...setFieldValue
<DatePicker
name={'joinedAt'}
value={values['joinedAt']}
onChange={setFieldValue}
/>
I resolve this like
<DatePicker
name={'joinedAt'}
value={values['joinedAt']}
onChange={e => setFieldValue('joinedAt', e)}
/>
Update on 2020-03-08:
You can use e.target.value on setFieldValue's second prop, depends on your custom input design. Thanks to Brandon.
If you have deeper nesting, you should use Formik Field.
Example:
<Formik
validationSchema={schema}
initialValues={initialValues}
onSubmit={(values, actions) => {}}
>
<Field name="colors" component={ColorsEditor} colors={colorArray}/>
</Formik>
const ColorsEditor = ({ field, colors, form, ...props }) => {
return (
<div>
<Button onClick={() => form.setFieldValue('colors', "myValue")}>
</Button>
</div>
)
}
So the Field component already include the form, where live the setFieldValue that you can use where you need. It also include the errors and needed fields for additional customization.
For html primitive input fields handleChange works like a charm, but for custom components, you've to use setFieldValue to change the value imperatively.
onChange={e => setFieldValue('joinedAt', e)}
The accepted answer didn't work for me and didn't show the selected date. It has been almost a year so there might be some changes with the implementation. Though this can be fix by using toDateString() like this
<DatePicker
name={'joinedAt'}
value={values['joinedAt']}
onChange={e => setFieldValue('joinedAt', e.toDateString())}
/>
The Formik solution for this is the useField() method. You may need to create a wrapper for components like DatePicker that you may not have source access to.
The documentation provides an example:
const MyTextField = ({ label, ...props }) => {
const [field, meta, helpers] = useField(props);
return (
<>
<label>
{label}
<input {...field} {...props} />
</label>
{meta.touched && meta.error ? (
<div className="error">{meta.error}</div>
) : null}
</>
);
};
In short, the method takes in the custom props which describe the field. Then you can expand the assigned field value and props in your custom field.
https://github.com/jaredpalmer/formik/issues/692
you need to set value manually if you are using setFieldValue method

React-Bootstrap-Typeahead allowNew select-on-blur

Is it possible to configure this so when allowNew is set that any new entry in this field would be selected on blur rather than clicking on the new item "menu"
EDITED:
This is my existing child component
<Typeahead
labelKey="label"
allowNew
selectHintOnEnter
options={props.campaignOptions}
placeholder="Campaign Name..."
onChange={props.campaignName}
/>
And this is my parent component...
campaignName (campaign){
campaign.length ? this.setState({campaignSelected:campaign}) : this.setState({campaignSelected:''})
}
...
<FormGroup>
<Campaign
campaignName={this.campaignName.bind(this)}
campaignOptions={[...new Set(this.props.records.map(options => options.campaign))]}/>
</FormGroup>
It's possible in the single-select case. Here's how you could do it:
class MyComponent extends React.Component {
state = {
selected: [],
text: '',
};
render() {
const {selected, text} = this.state;
return (
<Typeahead
allowNew
onBlur={(e) => this.setState({selected: text ? [text] : []})}
onChange={selected => this.setState({selected})}
onInputChange={(text) => this.setState({text})}
options={this.props.options}
selected={selected}
/>
);
}
}
Note that the code above simply sets the input value as the selection. You most likely want to convert the string to an object that has a unique identifier, like an ID.
It's not possible to do it in the multi-select case because you'd need to clear just the text input (not the selections) after the selecting the text, and there's no API for doing that.
Thanks for the advice, but I managed to get this to work with a much simpler approach that means that I don't need to use onBlur and I just store the onInputChange in the state in the parent.
const {campaignOptions, campaignValue, campaignName} = this.props;
...
<Typeahead
labelKey="label"
allowNew
placeholder="Campaign Name..."
onInputChange={campaignName}
options={campaignOptions}
selected={campaignValue}
/>

Resources