react-hook-form: how to get the select value - react-select

I am using react-hook-form with react-select. The below is the code
import CreatableSelect from "react-select/creatable";
const scriptOptions = [
{ value: "imd", label: "Immediate" },
{ value: "sch", label: "Scheduled" },
];
<Controller
name="resetType"
control={control}
render={({ field }) => (
<CreatableSelect
{...field}
options={scriptOptions}
/>
)}
/>
the value of resetType looks like
resetType: {
label: "Immediate"
value: "imd"
}
instead I want
resetType: "imd"
How to get this done

Related

React-select with react-hook-form

I have a credit card component. when user select expire month or expire year from select, I want to get value in p tag. Controller code is here, if I use render with controller its working but not giving error.
<Controller
as={<Select options={years} />}
name="expiryYear"
onChange={(inputValue) => changeValue(inputValue.value)}
control={control}
defaultValue={null}
rules={{
required: true
}}
/>
How it giving error when its null and get value in the p tag?
and here is the sandbox link https://codesandbox.io/s/cool-http-rbzfp
I think you want to use watch/usewatch to retrieve the input value:
https://react-hook-form.com/api#watch
https://react-hook-form.com/api#useController
import React, { useState } from "react";
import { useForm, Controller } from "react-hook-form";
import Select from "react-select";
const CreditCardForm = ({
cardInfo: { number, expiryMonth, expiryYear },
onChange
}) => {
const months = [
{ value: "01", label: "01" },
{ value: "02", label: "02" },
{ value: "03", label: "03" },
{ value: "04", label: "04" },
{ value: "05", label: "05" },
{ value: "06", label: "06" },
{ value: "07", label: "07" },
{ value: "08", label: "08" },
{ value: "09", label: "09" },
{ value: "10", label: "10" },
{ value: "11", label: "11" },
{ value: "12", label: "12" }
];
const years = [
{ value: "2021", label: "2021" },
{ value: "2022", label: "2022" },
{ value: "2023", label: "2023" },
{ value: "2024", label: "2024" },
{ value: "2025", label: "2025" },
{ value: "2026", label: "2026" },
{ value: "2027", label: "2027" },
{ value: "2028", label: "2028" },
{ value: "2029", label: "2029" }
];
const { register, errors, watch, formState, control } = useForm({
mode: "all",
reValidateMode: "onBlur"
});
console.log(watch());
function changeValue(inputValue) {
onChange({
key: "expiryMonth",
value: inputValue.label
});
}
function changeValue2(inputValue) {
onChange({
key: "expiryYear",
value: inputValue.label
});
}
return (
<form>
<div className="form-group expires">
<div className="expires__select">
{errors.expiryMonth && (
<span className="input__error-message">required</span>
)}
<Controller
as={<Select options={months} />}
name="expiryMonth"
// onChange={(inputValue) => changeValue(inputValue.value)}
control={control}
defaultValue={null}
rules={{
required: true
}}
/>
</div>
<div className="expires__select">
{errors.expiryYear && (
<span className="input__error-message">required</span>
)}
<Controller
as={<Select options={years} />}
name="expiryYear"
// onChange={(inputValue) => changeValue2(inputValue.value)}
control={control}
defaultValue={null}
rules={{
required: true
}}
/>
</div>
</div>
</form>
);
};
export default CreditCardForm;

react-native-print print of documents with data set in react native using html

Is there any way to display my data set into the html within async printHTML() I am using react native. Hope anyone can help me, It would be gladly appreciated, I've been working on it for how many hours. Thank you!
I tried using this way but it is not working, i just diaplay {dataSet1 ? dataSet1.map((dataSet1 , index) => ({dataSet1 .name} )) : No data} as a text
async printHTML() {
await RNPrint.print({
html: '<h1>Heading 1</h1>{dataSet1 ? dataSet1.map((dataSet1 , index) => (<div>{dataSet1 .name}</div> )) : <div>No data</div>}'
})
}
this is the dataset i want to display
const dataSet1 = [
{
name: "Johson",
amount: 30000,
sex: 'M',
is_married: true
},
{
name: "Monika",
amount: 355000,
sex: 'F',
is_married: false
},
{
name: "John",
amount: 250000,
sex: 'M',
is_married: false
},
{
name: "Josef",
amount: 450500,
sex: 'M',
is_married: true
}
];
Here is my Function
async printHTML() {
await RNPrint.print({
html: `<h1>Custom converted PDF Document</h1>
<h1>Custom converted PDF Document</h1>
<h1>Custom converted PDF Document</h1>
<h1>Custom converted PDF Document</h1>
`,
})
}
Andt this is my render component
render(){
return(
<Container style={{backgroundColor: '#f4f5f9'}}>
<View>
<View style={styles.container}>
<Button onPress={this.printHTML} title="Print HTML" />
</View>
</View>
</Container>
)
}
}
insert my data in an state
this.state = {
loading: false,
sound: 'off',
selectedPrinter: null,
dataSet1: [
{
name: "Johson",
amount: 30000,
sex: 'M',
is_married: true
},
{
name: "Monika",
amount: 355000,
sex: 'F',
is_married: false
},
{
name: "John",
amount: 250000,
sex: 'M',
is_married: false
},
{
name: "Josef",
amount: 450500,
sex: 'M',
is_married: true
}
]
}
Get the data to be displayed in table
renderTableData(){
return this.state.dataSet1.map((dataSet1, index) => {
const { name, amount, sex } = dataSet1
return (
`<tr key=${index}>
<td>${name}</td>
<td>${amount}</td>
<td>${sex}</td>
</tr>`
)
})
}
Call the function here
async printHTML() {
let html_content =
`<h1>Hello, UppLabs!</h1>
<table>
<tbody>
${this.renderTableData()}
</tbody>
</table>`
await RNPrint.print({
html : html_content })
}
change the button on press
render(){
return(
<Container style={{backgroundColor: '#f4f5f9'}}>
<View>
<Button onPress={() => {this.printHTML()}} title="Print HTML" />
</View>
</View>
</Container>
)
}

React Native - Connecting Two RNCPickerSelect's from 'react-native-picker-select'

How do I change the 'items' from a 'RNCPickerSelect' when I've selected a value from another 'RNCPickerSelect'?
For example, when I select a value called 'brand' from a RNCPickerSelect, the other RNCPickerSelect displays the 'models' associated with that specific 'brandName'. Basically, I want the 'items' from the other RNCPickerSelect to be influenced by the first RNCPickerSelect.
Here's the code:
================================Brands===================================
<RNPickerSelect
pickerProps={{ style: {overflow: 'hidden' } }}
onValueChange={(value) => console.log(value)}
placeholder={brandplaceholder}
// style={styles.dropbox}
items={[
{ label: 'brand1', value: 'brand1' },
{ label: 'brand2', value: 'brand2' },
{ label: 'brand3', value: 'brand3' },
]}
onValueChange={(val) => setBrand(val)}
/>
==========================================================================
=================================Models===================================
<RNPickerSelect
pickerProps={{ style: {overflow: 'hidden' } }}
onValueChange={(value) => console.log(value)}
placeholder={brandplaceholder}
// style={styles.dropbox}
items={[
{ label: 'model1', value: 'model1' },
{ label: 'model2', value: 'model2' },
{ label: 'model3', value: 'model3' },
]}
onValueChange={(val) => setModel(val)}
/>
==========================================================================
===============================Model Ideas================================
items={[
{ label: 'model4', value: 'model4' },
{ label: 'model5', value: 'model5' },
{ label: 'model6', value: 'model6' },
]}
**and**
items={[
{ label: 'model7', value: 'model7' },
{ label: 'model8', value: 'model8' },
{ label: 'model9', value: 'model9' },
]}
==========================================================================
Thanks!
With the codes provided by #FreakyCoder, I've successfully fixed and improved the 'RNCPickerSelect'. I have adjusted the code to fit my project and have added some extra lines of codes as well. Thanks again #FreakyCoder!
The Sample Codes:
export default function MainPage() {
//===============Example Selections===============//
const firstPick = [
{ label: 'Football', value: 'football' },
{ label: 'Baseball', value: 'baseball' },
{ label: 'Hockey', value: 'hockey' },
];
const secondPick = [
{ label: 'Football2', value: 'football2' },
{ label: 'Baseball2', value: 'baseball2' },
{ label: 'Hockey2', value: 'hockey2' },
];
const thirdPick = [
{ label: 'Football3', value: 'football3' },
{ label: 'Baseball3', value: 'baseball3' },
{ label: 'Hockey3', value: 'hockey3' },
];
//================================================//
const [dynamicPickerArr, setDynamicPickerArr] = useState(HondaModel)
return(
<RNPickerSelect
onValueChange={(value) => { setModel(value)
// Magic here
// Your changed value logic should be here
if(value=='football')
return Football=setDynamicPickerArr(thirdPick)
else if(value=='baseball')
return Baseball=setDynamicPickerArr(secondPick)
else if(value=='hockey')
return Baseball=setDynamicPickerArr(firstPick)
}
}
items={[
{ label: 'Football', value: 'football' },
{ label: 'Baseball', value: 'baseball' },
{ label: 'Hockey', value: 'hockey' },
]}
/>
<RNPickerSelect
onValueChange={(value) => console.log(value)}
items={dynamicPickerArr}
/>
)
}
you can do that with a simple state logic. When the first picker selects, it will update the other picker's predefined items array.
import React from "react";
import RNPickerSelect from 'react-native-picker-select';
const firstPick = [
{ label: 'Football', value: 'football' },
{ label: 'Baseball', value: 'baseball' },
{ label: 'Hockey', value: 'hockey' },
]
const secondPick = [[
{ label: 'Football2', value: 'football2' },
{ label: 'Baseball2', value: 'baseball2' },
{ label: 'Hockey2', value: 'hockey2' },
]
export const Dropdown = () => {
const [dynamicPickerArr, setDynamicPickerArr] = useState(firstPick)
return (
<RNPickerSelect
onValueChange={(value) => {
// Magic here
// Your changed value logic should be here
setDynamicPickerArr(secondPick)}
}
items={[
{ label: 'Football', value: 'football' },
{ label: 'Baseball', value: 'baseball' },
{ label: 'Hockey', value: 'hockey' },
]}
/>
<RNPickerSelect
onValueChange={(value) => console.log(value)}
items={}
/>
);
};

react-select Render custom component as SingleValue

I need to display an icon before the selected value using react-select and typescript.
This is what I tried so far:
SingleValue: React.SFC<SingleValueProps<OptionType>> = ({ children, ...props }) => (
<components.SingleValue {...props}>
<i className={`fal fa-${this.props.icon} has-text-grey-light`} /> {children}
</components.SingleValue>
)
The main issue is with type definitions that expects that children passed to components.SingleValue must be a string.
You don´t have to use the standard components. You can easlily create a custom one but still keep the styles it needs.
The only requirement you need is emotion to get the styles the SingleValue component uses.
/**
* This Example uses the `FontAwesome` React library.
**/
const options = [
{ label: "Value A", value: "a", icon: faCoffee },
{ label: "Value B", value: "b", icon: faCar },
{ label: "Value C", value: "c", icon: faMobile },
{ label: "Value D", value: "d", icon: faCircle },
{ label: "Value E", value: "e", icon: faSquare }
];
const SingleValue = ({
cx,
getStyles,
selectProps,
data,
isDisabled,
className,
...props
}) => {
console.log(props);
return (
<div
className={cx(
emotionCss(getStyles("singleValue", props)),
{
"single-value": true,
"single-value--is-disabled": isDisabled
},
className
)}
>
<FontAwesomeIcon icon={data.icon} style={{ marginRight: 10 }} />
<div>{selectProps.getOptionLabel(data)}</div>
</div>
);
};
export default class MySelect extends Component {
render() {
return (
<Select
options={options}
components={{ SingleValue }}
styles={{
singleValue: (provided, state) => ({
...provided,
display: "flex", // To keep icon and label aligned
alignItems: "center"
})
}}
/>
);
}
}
Working example

How to set multiple select with #shoutem/ui DropDownMenu?

I use DropDownMenu and take a reference from official doumcn https://shoutem.github.io/docs/ui-toolkit/components/dropdown-menu
I want to set two DropDownMenu the first is for zone and the second is for city, if user select the zone like East the second DropDownMenu should set the value E1、E2
Here is my code:
import React, { Component } from 'react';
import { View } from 'react-native';
import { DropDownMenu, Text } from '#shoutem/ui';
class TestConfirm extends Component {
constructor(props) {
super(props);
this.state = {
zone: [
{
id: 0,
brand: "North",
models:
{
model: "Audi R8",
image: {
url: "https://shoutem.github.io/img/ui-toolkit/dropdownmenu/Audi-R8.jpg"
},
description: "North Description"
},
children: [{
name: "N1",
id: 10,
},{
name: "N2",
id: 17,
}]
},
{
id: 1,
brand: "West",
models: {
model: "Chiron",
image: {
url: "https://shoutem.github.io/img/ui-toolkit/dropdownmenu/Chiron.jpg"
},
description: "West Description"
},
children: [{
name: "W1",
id: 10,
},{
name: "W2",
id: 17,
}]
},
{
id: 2,
brand: "East",
models: {
model: "Dodge Viper",
image: {
url: "https://shoutem.github.io/img/ui-toolkit/dropdownmenu/Dodge-Viper.jpg"
},
description: "East Description"
},
children: [{
name: "E1",
id: 10,
},{
name: "E2",
id: 17,
}]
},
],
}
}
render() {
const selectedZone = this.state.selectedZone || this.state.zone[0];
console.log('selectedZone =>');
console.log(selectedZone);
console.log('selectedZone.children =>');
console.log(selectedZone.children);
return (
<Screen>
<DropDownMenu
styleName="horizontal"
options={this.state.zone}
selectedOption={selectedZone ? selectedZone : this.state.zone[0]}
onOptionSelected={(zone) => this.setState({ selectedZone: zone })}
titleProperty="brand"
valueProperty="cars.model"
/>
<Text styleName="md-gutter-horizontal">
{selectedZone ?
selectedZone.models.description :
this.state.zone[0].models.description}
</Text>
<DropDownMenu
styleName="horizontal"
options={selectedZone.children}
selectedOption={selectedZone ? selectedZone : this.state.zone[0].children}
onOptionSelected={(city) => this.setState({ selectedZone: city })}
titleProperty="name"
valueProperty="cars.model"
/>
</Screen>
);
}
}
export default TestConfirm;
Here is my screen look like this:
If i select East it will show error
Invalid `selectedOption` {"id":2,"brand":"East","models":{"model":"Dodge Viper","image":{"url":"https://shoutem.github.io/img/ui-toolkit/dropdownmenu/Dodge-Viper.jpg"},"description":"East Description"},"children":[{"name":"E1","id":10},{"name":"E2","id":17}]}, DropDownMenu `selectedOption` must be a member of `options`.Check that you are using the same reference in both `options` and `selectedOption`.
I check my console.log will look like this:
The key children under the name is what i want to put it into my second DropDownMenu
I have no idea how to do next step. Any help would be appreciated.
Thanks in advance.
selectedOption property for the DropDownMenu component expects a single object but this.state.zone[0].children is an array. You can change it to this.state.zone[0].children[0] to fixed the problem.
Also when you change the city dropdown you are updating the zone value in state. This will cause a bug. Try fixing it with setting a different value in state and checking that value for the city dropdown
Sample
render() {
const { zone, selectedZone, selectedCity } = this.state
return (
<Screen>
<DropDownMenu
styleName="horizontal"
options={zone}
selectedOption={selectedZone || zone[0]}
onOptionSelected={(zone) =>
this.setState({ selectedZone: zone, selectedCity: zone.children[0] } )
}
titleProperty="brand"
valueProperty="cars.model"
/>
<Text styleName="md-gutter-horizontal">
{selectedZone ?
selectedZone.models.description :
this.state.zone[0].models.description}
</Text>
<DropDownMenu
styleName="horizontal"
options={selectedZone ? selectedZone.children : zone[0].children } // check if zone selected or set the defaul zone children
selectedOption={selectedCity || zone[0].children[0] } // set the selected city or default zone city children
onOptionSelected={(city) => this.setState({ selectedCity: city })} // set the city on change
titleProperty="name"
valueProperty="cars.model"
/>
</Screen>
);
}