Radio Button Reset - reactjs

I'm using this package Radio Button. It's working fine but I need to reset the selected value, for that I can not find any solution there.

you can change state to render new radio button - https://snack.expo.dev/iiHkFYpLV
import React, { useState } from "react";
import { View, StyleSheet, Button, Alert } from "react-native";
import RadioButtonRN from 'radio-buttons-react-native';
const App = () => {
const [show,setShow] = React.useState(true);
const data = [
{
label: 'data 1'
},
{
label: 'data 2'
}
];
React.useEffect(()=>{
if(!show) setShow(true)
},[show])
const resetHandler = () =>{
setShow(false)
}
return (
<View style={styles.container}>
{show &&
<RadioButtonRN
data={data}
selectedBtn={(e) => console.log(e)}
/>
}
<Button title='reset' onPress={resetHandler} />
</View>
);
}
const styles = StyleSheet.create({
container: {
paddingTop:100,
}
});
export default App;

the package does not have the reset functionality but there is a PR pending for the same feature. Whole package is in a single file only, so what you can do is copy package file to your code and add the feature related code from the PR.
or you can use another package ;)

Related

How can I press individual option in actionsheet in React Native?

I am still new to React Native. I have an actionsheet with two options and a cancel option. I am having trouble understanding how to make each option do something different when pressed.
My code:
import React, { useRef } from "react"
import ActionSheet from 'react-native-actionsheet'
import { View, Text, Pressable } from "react-native";
import Icon from 'react-native-vector-icons/FontAwesome';
const ActionSheet = () => {
let actionSheet = useRef();
let optionArray = ['Orange', 'Cherry', 'Cancel'];
const showActionSheet = () => {
actionSheet.current.show();
}
return (
<View
<Pressable onPress={showActionSheet}>
<View>
<Text>Choose Fruit</Text>
<Icon name="angle-right" size={15}/>
</View>
</Pressable>
<ActionSheet
ref={actionSheet}
options={optionArray}
cancelButtonIndex={2}
onPress={{????}}
/>
</View>
);
};
What I'd like to do is navigate to a different screen when an option is pressed
Would appreciate any help. Thank you in advance!
The onPress function provides an index argument. Thus consider the following code snippet.
const onActionSelect = (index) => {
if (index === 1) {
// first action pressed
} else if (index === 2) {
// second action pressed
}
// and so on
}
<ActionSheet
ref={actionSheet}
options={optionArray}
cancelButtonIndex={2}
onPress={onActionSelect}
/>

How to use onSubmitEditing in react-native?

I tried to use onKeyPress, but since android doesnt get hard keyboard input, i want to use onSubmitEditing,
I have two TextInputs, what I want to do is that when I press on Enter when i am in textInput for firstName, it should be focused on next textInput
const firstNameRef = useRef(null);
const lastNameRef = useRef(null);
useEffect(()=> {
firstNameRef.current.focus();
}, [])
const firstKeyPress = (e) => {
if(e.key ==="Enter"){
lastNameRef.current.focus();
}
}
input.js
import React from "react";
import { TextInput, View } from "react-native";
const Input = React.forwardRef(({placeholder,onKeyPress},ref) => {
return(
<View>
<TextInput ref={ref} placeholder={placeholder}/>
</View>
)
})
export default Input;
Will I only add blurOnSubmit={false} onSubmitEditing={()=>lastNameRef.current.focus()} on Input component?
Yes, it worked.
I only added blurOnSubmit={false} onSubmitEditing={()=>lastNameRef.current.focus()} for the first TextInput, and called it as props, in input.js as blurOnSubmit={blurOnSubmit} onSubmitEditing={onsubmitEditing}
When i press on Enter while in first TextInput, it goes to other input.

React Native Navigation: Check if drawer is opened or not

i have a component that is outside the Drawer tag but it's inside a NavigationContainer.
So i used useRef from react to get navigate method .
So i use this example: Navigating without navigation prop
But now, i can't get the state of the drawer (is it opened or closed).
Here's my App component:
import 'react-native-gesture-handler';
import React from 'react';
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { Provider } from "react-redux";
import GetInformationByLocation from "./reducers/GetInformationByLocation";
import Wrapper from './components/Wrapper';
import { createDrawerNavigator } from '#react-navigation/drawer';
import { NavigationContainer } from '#react-navigation/native';
import GeoDisplay from "./components/GeoDisplay";
import { Text } from "react-native";
import { navigationRef } from "./helpers/Navigator";
const store = createStore(GetInformationByLocation, applyMiddleware(thunk));
/*
* TODO:
* 1. Wrap everything with parent component
* 2. Search bar
* 3. Save searched cities.
* 4. Check if the city is undefined and suggest nearest city.
* 5. Animated background
* 6. Fancy and animated font
* 7. Setup menu преди показване на приложението
*/
const Drawer = createDrawerNavigator();
const App = () => {
return (
<Provider store={store}>
<NavigationContainer ref={navigationRef}>
<Wrapper />
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={GeoDisplay} />
</Drawer.Navigator>
</NavigationContainer>
</Provider >
);
}
export default App;
and my Wrapper.js Component:
import React, { useEffect, useState } from 'react';
import { StyleSheet, View, StatusBar } from 'react-native';
import { SearchBar, Header } from 'react-native-elements';
import { MainUI } from '../styling/UI';
import * as Navigator from "../helpers/Navigator";
import { DrawerActions } from "#react-navigation/native";
const Wrapper = (props) => {
const [search, setSearch] = useState(true);
const openDrawer = () => {
Navigator.navigationRef.current.dispatch(DrawerActions.openDrawer())
setSearch(false);
}
useEffect(() => {
}, []);
return (
<>
<StatusBar backgroundColor={"#011E25"} />
<Header
leftComponent={{ icon: 'menu', color: '#fff', onPress: () => { openDrawer() } }}
centerComponent={{ text: 'COVID Bulgaria', style: { color: '#fff' } }}
rightComponent={{ icon: 'home', color: '#fff' }}
backgroundColor={'#011E25'}
/>
{search &&
<View>
<SearchBar placeholder="Търси град" containerStyle={MainUI.searchContainer} />
</View>
}
</>
)
}
export default Wrapper;
I dispatch openDrawer() action with navigationRef
Navigator.navigationRef.current.dispatch(DrawerActions.openDrawer())
but can't get status of the drawer.
I've tried many ways but not work.
Thanks in advance.
You can check if drawer is open by getting the navigation state:
const state = navigationRef.current.getRootState();
const isDrawerOpen = state.history.some((it) => it.type === 'drawer');
The above code assumes that drawer is at root. If it's nested, you'll need to traverse the state to find the state object with type: 'drawer'.
It's not clear why you need to check it from the question. Normally you shouldn't need to check it. If you dispatch DrawerActions.openDrawer() if drawer is already open, nothing will happen. So the check is unnecessary. If you want to close the drawer if it was open, you can dispatch DrawerActions.toggleDrawer() instead.
You can create a helper class like:
class DrawerHandler() {
openDrawer() {
this.drawerOpened = true;
}
closeDrawer() {
this.drawerOpened = false;
}
getDrawerStatus() {
return this.drawerOpened;
}
}
export default new DrawerHandler();
Use open and close functions on drawer opening and closing and get function to get status of the drawer

React Native save change switch with Async Storage

Im new in React Native, I have a problem with Switch, I want to save changes, dark mode and Switch, when I turn off the app and come back my changes should be saved. When I close the app, my switch came back to first position and dark mode does not work. I know that Im doing something wrong, but I did not mobile app and this is my first time and I dont know how to use AsyncStorage in this App to work this. Can somebody help me solve this problem?
import React, { createContext, useState, useEffect } from 'react';
import { AsyncStorage } from 'react-native';
export const DarkModeContext = createContext();
export default function DarkModeContextProvider(props) {
const [switchMode, setSwitchMode] = useState(false);
useEffect(() => {
let switch1 = switchMode;
AsyncStorage.setItem('switch1', JSON.stringify(switch1));
});
const SwitchThis = () => {
setSwitchMode(!switchMode);
};
return (
<DarkModeContext.Provider
value={{
switchMode,
SwitchThis
}}
>
{props.children}
</DarkModeContext.Provider>
);
}
and next component:
import React, { useState, useContext } from 'react';
import { View, ScrollView, TouchableOpacity, Text, AsyncStorage } from 'react-native';
import { List } from 'react-native-paper';
import BackgroundImage from './BackgroundImage';
import Clock from './Clock';
import TabIcon from './TabIcon';
import AddButton from './AddButton';
import { DarkModeContext } from './app-context';
const HomeScreen = () => {
const { switchMode } = useContext(DarkModeContext);
displayData = async () => {
try {
let switch1 = await AsyncStorage.getItem('switch1', function (err, switch1) {
JSON.parse(switch1)
}
)
return switch1
}
catch (error) {
return error
}
}
return (
<View
style={{
flex: 1,
backgroundColor: !switchMode ? 'white' : '#353535'
}}
>
<BackgroundImage fabButton={<AddButton/>}>
<Clock />
</BackgroundImage>
<ScrollView>
<List.Section>
<List.Subheader style={{ color: !switchMode ? 'black' : 'white' }}>
Task List
</List.Subheader>
<TouchableOpacity onPress={displayData}>
<Text>Click displayData</Text>
</TouchableOpacity>
</List.Section>
</ScrollView>
</View>
);
};
You are importing AsyncStorage from 'react-native' which is deprecated
use #react-native-community/react-native-async-storage
npm i #react-native-community/react-native-async-storage
And on your home screen you are not calling the function displayData() so how is data supposed to be displayed without function call.
and i do suggest making separate functions for writing and reading from async storage, it will help you reduce your code and time.
Like this:
let storeData=(name, obj)=> {
return new Promise((resolve,reject)=>{
let jsonOfItem = JSON.stringify(obj)
AsyncStorage.setItem(name, jsonOfItem).then(r=>resolve(jsonOfItem))
.catch(e=>reject(e))
})
}
let readData=(name)=> {
return new Promise((resolve,reject)=>{
//we want to wait for the Promise returned by AsyncStorage.setItem()
//to be resolved to the actual value before returning the value
AsyncStorage.getItem(name).then(r=> resolve(JSON.parse(r)) )
.catch(e=>reject(e))
})
}
//Now you can just read write easily in async function like this:
let fetchedData = await readData("key")
//and for storing data.
storeData("key",object)

How to set the internal state to an empty string when using mui-rte for a chat message input

I am using mui-rte, which is a nice Material-ui wrapper around draftjs:
https://github.com/niuware/mui-rte.git
I want to use MUIRichTextEditor for the input field for a web chat client. I have hit a roadblock on how to set the internal state to an empty string after hitting the send button. The RTE editor component looks like this:
import React, {useState, useEffect} from "react";
import MUIRichTextEditor from "mui-rte";
import {convertToRaw, EditorState} from 'draft-js'
import {stateFromMarkdown} from "draft-js-import-markdown";
import { ThemeProvider } from '#material-ui/styles';
import { createMuiTheme, useTheme} from '#material-ui/core/styles';
const local_theme_overrides = {
overrides: {
MUIRichTextEditor: {
root: {
marginTop: 20,
width: "80%"
},
editor: {
border: "1px solid gray",
borderRadius: 4
}
}
}
};
export default function RichTextEditor(props)
{
const { initialValue, onChange, ...rest } = props;
const [initial, setInitial] = useState('');
useEffect(() => {
const init_state = EditorState.createWithContent(stateFromMarkdown(initialValue));
setInitial(JSON.stringify(convertToRaw(init_state.getCurrentContent())));
onChange(init_state);
}, []);
const theme = useTheme();
const [localTheme, setLocalTheme] = useState(theme);
useEffect(() => {
setLocalTheme(Object.assign({...theme}, local_theme_overrides));
}, []);
return (
<ThemeProvider theme={localTheme}>
<MUIRichTextEditor
onChange={onChange}
value={initial}
{...rest}
>
</MUIRichTextEditor>
</ThemeProvider>
);
}
The parent uses the field like this:
const [message_content, setMessageContent] = useState('');
function sendMessage() {
if (message_content === '')
return;
let rte_markdown = stateToMarkdown(message_content.getCurrentContent());
channel.sendMessage(rte_markdown);
// I would like to reset or re-render the mui-tre component after sending the message
//setMessageContent('');
}
.....
<RichTextEditor
label={"Write a message to " + name}
initialValue={''}
onChange={data => setMessageContent(data)}
placeholder={"Write a message to " + name}
controls={[]}
/>
<Button
autoFocus
onClick={() => sendMessage()}
disabled={message_content === ''}
>
Send
</Button>
When the sent button is pressed the message gets deliver to the chat channel but I am falling short of being able to re-set or force re-render of the RTE component. Any ideas on how to do that?
You can set the value property of the MUI text editor to an empty content state. The state has to be stringified and raw.
One way is to import the EditorState object and convertToRaw method from the draft-js library (which mui-rte is built on):
import { EditorState, convertToRaw } from 'draft-js'
const emptyContentState = JSON.stringify(
convertToRaw(EditorState.createEmpty().getCurrentContent())
<MUIRichTextEditor value={emptyContentState} />

Resources