React material UI close when the value selected - multi select - react-native

I am using react material UI for building my components. I am using react multi-select to get multiple values from the user.
<FormControl className={clsx(classes.formControl, classes.noLabel)}>
<Select
multiple
value={personName}
onChange={handleChange}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
}}
input={<Input />}
renderValue={(selected) => {
if (selected.length === 0) {
return <em>Placeholder</em>;
}
return selected.join(", ");
}}
MenuProps={MenuProps}
inputProps={{ "aria-label": "Without label" }}
>
<MenuItem disabled value="">
<em>Placeholder</em>
</MenuItem>
{names.map((name) => (
<MenuItem
key={name}
value={name}
style={getStyles(name, personName, theme)}
>
{name}
</MenuItem>
))}
</Select>
</FormControl>
It's working fine. But I need to close the dropdown when the user selects the value. But now it's closed only when the blur event triggers.
Is there any option to close the dropdown when the user selects any values?
Thanks in advance

Probably you can solve this by using the useRef hook.
Add the reference to the select and in the change handler you can try to close it by using ref.current.close().
import React , {useRef} from 'react';
const ref = useRef()
<FormControl className={clsx(classes.formControl, classes.noLabel)}>
<Select
multiple
value={personName}
onChange={handleChange}
ref={ref}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
}}
input={<Input />}
renderValue={(selected) => {
if (selected.length === 0) {
return <em>Placeholder</em>;
}
return selected.join(", ");
}}
MenuProps={MenuProps}
inputProps={{ "aria-label": "Without label" }}
>
<MenuItem disabled value="">
<em>Placeholder</em>
</MenuItem>
{names.map((name) => (
<MenuItem
key={name}
value={name}
style={getStyles(name, personName, theme)}
>
{name}
</MenuItem>
))}
</Select>
</FormControl>
const handleChange = (event) =>{
....
ref.current.close();
}

Related

modal not working correctly in native base

I want when i click the button, opening the modal. But modal is not opening correctly. And it is not readable.
Here is in my modal code :
<Modal
isOpen={showModal}
>
<Modal.Content top="-60" maxWidth={400} height={300}>
<Modal.CloseButton />
<Modal.Header> bilgiler</Modal.Header>
<Modal.Body>
<Text>09.08.2001</Text>
{/* <Select
minWidth="200"
accessibilityLabel="Choose Service"
placeholder="Son ölçüm tarihi seçiniz.."
_selectedItem={{
bg: "teal.600",
endIcon: <CheckIcon size="5" />
}} mt={1}
>
</Select>*/}
<Text>Adi ve soyadi</Text>
</Modal.Body>
<Modal.Footer>
<Button.Group space={2}>
<Button variant="ghost" colorScheme="blueGray" onPress={() => setShowModal(false)} >
Çıkış
</Button>
<Button onPress={() => setShowModal(false)} >
Kaydet
</Button>
</Button.Group>
</Modal.Footer>
</Modal.Content>
</Modal>
and pressable code :
<Box flex="1" >
<Pressable left={290} top="-35" onPress={() => setShowModal(true)}>
<Image size={7} source={require('../assets/clock.png')} />
</Pressable>
</Box>
I try to change pressable but it not working
Try this
Create a component for Model to reuse or use can have it in screen itself.
Modal.js
const Mdal = ({ ...props }) => {
const { onInputChanged, showModal, onClose, header, inputTitle, ...p }
= props;
const [isOpen, setIsOpen] = useState(false);
return (
<Modal
isOpen={showModal}
onClose={onClose}
_backdrop={{
_dark: {
bg: "coolGray.800",
},
bg: "warmGray.50",
}}
>
<Modal.Content borderWidth={2} width="500" maxWidth="93%" maxH="600">
<Modal.CloseButton />
<Modal.Header flexDirection="row">{header}</Modal.Header>
<Modal.Body>
<Text>Your View</Text>
</Modal.Body>
<Modal.Footer background={COLOR.card_action_bg}>
<Button.Group space={2}>
<Button
colorScheme="warmGray"
onPress={() => {
onInputChanged("if any passing value");
}}
>
Save
</Button>
<Button
colorScheme="red"
onPress={() => {
onClose();
}}
>
Cancel
</Button>
</Button.Group>
</Modal.Footer>
</Modal.Content>
</Modal>
);
};
export default Mdal;
In the screen where you want modal :
import { Model } from "the path if it is as component"
const [showModal, setShowModal] = useState(false);
Place it inside your view
<Modal
onInputChanged={onInputChanged}
showModal={showModal}
onClose={() => setShowModal(false)}
header={"(" + ticketId + ") - " + action}
inputTitle={"Reason for transfer"}
/>
onInputChanged - is the function
const onInputChanged = (changedText) => {
//received selected value in changedText
}
change the state of showModal to true on your pressable view(onPress) ->
setShowModal(true);

How to make alert on click of button

Is there a way to make Alert on click not using the alert method but Alert tag. Currently I tried using usestate but didn’t work
Hard to know what your problem is without seeing code but this is the general approach to show tag based components. Don't forget to revert the state value on dismissal.
const [showAlert, setShowAlert ] = useState(false);
return (
<>
{showAlert ?
<Alert {...otherPropsHere} />
: <View/> }
<Button title="Press Me" onPress={() => {setShowAlert(true)} />
</>
)
If the tag has a 'visible' prop then it would be more like this
const [showAlert, setShowAlert ] = useState(false);
return (
<>
<Alert visible={showAlert} {...otherPropsHere} />
<Button title="Press Me" onPress={() => {setShowAlert(true)} />
</>
)
If you need multiple alerts you could:
const [showAlertOne, setShowAlertOne ] = useState(false);
return (
<>
{showAlertOne ?
<Alert {...otherPropsHere} />
: <View/> }
{showAlertTwo ?
<Alert {...otherPropsHere} />
: <View/> }
<Button title="Show Alert One" onPress={() => {setShowAlertOne(true)} />
<Button title="Show Alert Two" onPress={() => {setShowAlertTwo(true)} />
</>
)
This isn’t the best way to do it but I think this should clear up the concept of what you are trying to do. A better way - if the alerts don’t show at the same time - is to have a single state object in which you store which alert you want to show. These could be an ENUM too to add a little safety.
This is the (partially) typed example with an enum and a wrapped component.
const myApp = () => {
enum AlertType = { One, Two, Three }
const [visibleAlert, setVisibleAlert ] = useState<AlertType | null>(null);
const VisibleAlert = (alertType:AlertType) => {
switch (visibleAlert) {
case AlertType.One:
return <Alert {otherPropsHere} />
break;
case AlertType.One:
return <Alert {otherPropsHere} />
break;
default:
return <View/>
break;
}
}>
return (
<>
<VisibleAlert alertType={visibleAlert} />
<Button title="Show Alert One" onPress={() => {setVisibleAlert(AlertType.One)} />
<Button title="Show Alert Two" onPress={() => {setVisibleAlert(AlertType.Two)} />
</>
)
}
Wrapping the modal in a component with its own state might be a good approach but let’s see what your issue is for sure first.

disable keyboard in react native while selecting from dropdown or picker?

how can I disable the keyboard when the user click the dropdown or the picker ?
The keyboard triggered by the input field is not closing while I click the picker or dropdown
<View picker style={style.PickerBox} >
<Picker
mode="dropdown"
iosIcon={<Icon name="arrow-down" />}
placeholder="Select Type"
onValueChange={Type => this.setState({ Type })}
selectedValue={this.state.shopType}
style={style.Picker}
>
{this.state.shopTypesArray.map(value => {
//loop the dropdown
return (
<Picker.Item label={value.value} value={value.value} />
);
})}
</Picker>
</View>
You can use Keyboard.dismiss() when you click on the dropdown/picker:
import { Keyboard } from "react-native"
...
yourFunc = () => {
Keyboard.dismiss()
//Your logic
}
Source: https://facebook.github.io/react-native/docs/keyboard
This will be triggered when you change the value inside the Picker:
<Picker
mode="dropdown"
iosIcon={<Icon name="arrow-down" />}
placeholder="Select Type"
onValueChange={Type => {
Keyboard.dismiss()
this.setState({ Type })
}}
selectedValue={this.state.shopType}
style={style.Picker}
>

Focus the input in the WebView with React native

Have you any idea to create a onFocus event in this input of the WebView ?
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<WebView
originWhitelist={['*']}
source={{ html: ' </br></br><form> <input type="text"
placeholder="name" onFocus=(*****)/> <input
type="text" placeholder="surname"/> <Button>Submit</Button>
</form>' }} />
</View>
)}}
I tried the usual onFocus but it doesn't work . I want to dispatch an event when i focus the input
To make a onFocusEvent to the input of the webview we have just to deal with postMessage and onMessage . Here is the full code :
let Script = `
document.getElementById("input").addEventListener("focus", function() {
var data = {
type: "OnFocusEvent",
message : "OnFocusEvent"
};
window.postMessage(JSON.stringify({data}),"*");
});
`;
<WebView
style={{ flex: 1 }}
source={{
html:
'</br></br></br></br><form > <input id="input" class="input" type="text"
placeholder="Product barcode "/></form>'
}}
keyboardDisplayRequiresUserAction={false} //ios
autoFocus={true} //android
injectedJavaScript={Script1}
automaticallyAdjustContentInsets={false}
allowFileAccessFromFileURLs={true}
scalesPageToFit={false}
mixedContentMode={"always"}
javaScriptEnabled={true}
javaScriptEnabledAndroid={true}
startInLoadingState={true}
onMessage={event => {
alert("You can do here whatever you want")
}}
onLoad={() => {}}
/>
There is closed Pull Request for that feature. For now, you can use react-native-enhance-webview
I hope that helps. Good luck.

how to use react native elements radio button with redux form?

I am using react elements components in my react-native application.
import React,{ Component } from 'react';
import { Field,reduxForm } from 'redux-form';
import { Text,Input } from 'react-native-elements';
import { View,Button } from 'react-native';
import {Icon,CheckBox} from 'react-native-elements';
const renderField=({label,keyboardType,name,icon,iconType,input:{onChange,...restInput}}) => {
return(
<View style={{flexDirection:'row'}}>
<Input onChangeText={onChange} {...restInput} keyboardType={keyboardType} placeholder={label} inputContainerStyle={{borderWidth:2,borderColor:'lightgrey',borderRadius:20}} inputStyle={{color:'grey'}} leftIcon={<Icon size={25} type={iconType} name={icon} color="grey" />} errorStyle={{fontSize:15}} errorMessage="error" />
</View>
)
}
const checkBoxField=({label,keyboardType,name}) => {
var val=true;
return(
<View >
<View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
<Text style={{fontSize:18}}>{label}</Text>
<CheckBox title='Male' checkedIcon='dot-circle-o' uncheckedIcon='circle-o' containerStyle={{backgroundColor:'transparent',borderWidth:0,padding:0}} textStyle={{fontSize:18}} />
<CheckBox title='Female' checkedIcon='dot-circle-o' uncheckedIcon='circle-o' containerStyle={{backgroundColor:'transparent',borderWidth:0,padding:0}} textStyle={{fontSize:18}} />
</View>
<View><Text style={{fontSize:15,color:'red'}}>error</Text></View>
</View>
)
}
const submit = values => {
console.log('submitting form', values)
}
const RegisterForm=props => {
const {handleSubmit}=props;
return(
<View style={{flex:1,flexDirection:'column',margin:20,justifyContent:'flex-start',alignItems:'center'}}>
<Field label="Username" component={renderField} name="username" icon="user" iconType="font-awesome" />
<Field label="Email" component={renderField} name="email" icon="email" iconType="zocial" />
<Field label="Gender" component={checkBoxField} name="gender" />
<Button title='SUBMIT' onPress={handleSubmit(submit)} />
</View>
)
}
const Register=reduxForm({
form:'register',
})(RegisterForm);
export default Register;
in the above code I am using redux form in my react-native application,by passing onChange() I can retrieve values of text input,but how can I retrieve the values of a radio button?currently the form contains text input values only,I need to add radio button values also. If the user select one value in the radio button I need to unselect other radio button how it will be possible?
You can use react-native-radio-input.
Its very simple to use.
import RadioGroup,{Radio} from "react-native-radio-input";
.
.
.
//Receive the checked value (ES6 syntax)
getChecked = (value) => {
// value = our checked value
alert(value)
}
<RadioGroup getChecked={this.getChecked}>
<Radio iconName={"lens"} label={"The first option"} value={"A"} />
<Radio iconName={"lens"} label={"The first option"} value={"B"} />
<Radio iconName={"lens"} label={"I need numbers"} value={1} />
<Radio label={"Is IconName Optional?"} value={"Yes"} />
<Radio label={"Show Sentence Value"} value={"This is a Sentence"} />
</RadioGroup>
.
.