How to use onSubmitEditing in react-native? - reactjs

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.

Related

Radio Button Reset

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

Use hook in export function - React Native

I want to write 1 common function that I will use in different functional components.
This generic function uses hooks and I get the error: Error: Invalid hook call. Hooks can only be called inside the body of a functional component.
Example of my code:
App.js
import React from 'react';
import {
Text,
TouchableOpacity,
} from 'react-native';
import { Change } from 'static/Change';
export default function App() {
return (
<TouchableOpacity
onPress={() => {
Change();
}}
>
<Text>Click Me!</Text>
</TouchableOpacity>
);
}
Change.js
import React from 'react';
export const Change = () => {
const [State, setState] = React.useState(0);
// Other hook work.
// The function returns nothing
};
What is my mistake and how can I fix it?
Hooks has some rules to follow - https://reactjs.org/docs/hooks-rules.html
Refactor code as below
import React from "react";
import { Text, TouchableOpacity } from "react-native";
function useChange() {
const [state, setState] = React.useState(0);
function change(value) {
setState(value);
}
return { change, state };
}
export default function App() {
const { change, state } = useChange();
return (
<TouchableOpacity
onPress={() => {
// Update state value on press
change(state + 1);
}}
>
<Text>Click Me!{state}</Text>
</TouchableOpacity>
);
}

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

react-redux-toastr: text input is blurred when the toast shows up

I using library react-redux-toastr for our project. This library works great, except this case: codesandbox:
import React from "react";
import { useCallback } from "react";
import debounce from "lodash/debounce";
import { toastr } from "react-redux-toastr";
export default function Input({ value, onChange }) {
const toast = useCallback(
debounce(() => {
toastr.error("Interupt your typing", "Sorry, I blur your text input");
}, 500)
);
const setValue = e => {
onChange(e.target.value);
toast();
};
return (
<input
style={{ width: 500 }}
type="text"
value={value}
onChange={setValue}
/>
);
}
Basically, we want to let user keep typing in, and debouncedly call some API to update the input to database. Everything an API call is successful, show the toast. However, whenever the toast is displayed, the text input is unfocused.
in the CodeSandbox demo, you can try to type in anything, and see what the problem is.
Thanks.

Resources