how can I clear Native-base Input text? - react-native

I try this
<Input placeholder="search...."
ref={(ref) => { this.SearchInput = ref; }}
/>
<Button transparent onPress={this.clear}>
<Ionicons name="ios-close" />
</Button>
and function:
clear = () => {
this.SearchInput.clear();
}
I get this error:
this.SearchInput.clear() is not a function

This is the running code, change ref to getRef and use this.SearchInput._root.clear(); instead of this.SearchInput.clear();
clear = () => {
this.SearchInput._root.clear();
}
render() {
return (
<Container>
<Header />
<Content>
<Item floatingLabel>
<Input placeholder="search...."
getRef={(ref) => this.SearchInput = ref}
/>
</Item>
<Button onPress={this.clear}>
<Ionicons name="ios-close" />
</Button>
</Content>
</Container>
);
}

I use value and state to achieve this functionality
here is the example:
<Input
value={ this.state.value }
onChangeText={ this.onTextChange }
/>
<Button onPress={this.clear}>
<Ionicons name="ios-close" />
</Button>
declare default value's value on constructor
this.state = {
value: ''
}
listen to onTextChange as follows, this make sure that the value on Input stay the same as we inserting, not blank forever:
onTextChange = (value) => {
this.setState({ value })
}
finally, on clear function
clear = () => {
this.setState({ value: '' })
}
just set back value to empty

i totally agree with Muhammad Hanzala as it worked for me on this but there is a little exception which is really important which i had to do to make it work be sure to add the reference of the text input to your constructor like this:
constructor()
{
...
this.SearchInput = React.createRef();
}
A full example will look like this in your input element...
<InputgetRef={(ref) => this.SearchInput = ref}/>
in your constructor :
constructor()
{
...
this.SearchInput = React.createRef();
}
and finally you can call:
this.SearchInput._root.clear();
and dont forget to clear your state..

Related

react-hook-form useFieldArray with React-Native

Is it possible to use ReactNative with useFieldArray from react-hook-form? I couldn't find any reference for that.
I'm trying to use it but I can't get the output data from the TextInputs. It looks like the onChange is not working, I tried to use the onChange prop but still couldn't make it.
Example:
const {
control,
formState: {errors},
register,
getValues,
handleSubmit,
} = useForm({
defaultValues: {
playerNameInput: [{playerName: ''}, {playerName: ''}],
},
});
const {fields, append, remove} = useFieldArray({
control,
name: 'playerNameInput',
});
return(
<>
{fields.map((player, index) => (
<View>
<Controller
control={control}
rules={{required: true}}
name="playerNameInput"
render={() => (
<TextInput
style={{width: 100}}
defaultValue={`${player.playerName}`}
{...register(`playerNameInput.${index}.playerName`)}
/>
)}
/>
</View>)}
<Button onPress={handleSubmit(data => console.log(data))}>
Save Changes
</Button>
</>
)

Is there a way to set a state with textinput when onChangeText is already in use?

Im trying to set a state with the values from a textinput (which is a reusable component), Im using onChangeText to setFieldValue (useFormikContext()), I also want to set a state which will be sending to the Parent component. I tried using onChange but noticed it saves the text without the last word/number, for instance if I type 0123456789, the setFieldValue gets 0123456789, but the other one (with onChange) gets only 012345678 (without 9).
Here is the code:
function AppFormField({ name, width, childToParent, ...otherProps }) {
const { setFieldTouched, setFieldValue, errors, touched, values } =
useFormikContext();
return (
<>
<TextInput
onBlur={() => setFieldTouched(name)}
onChangeText={(text) => setFieldValue(name, text)}
onChange={() => childToParent(bn)}
value={values[name]}
width={width}
{...otherProps}
/>
<ErrorMessage error={errors[name]} visible={touched[name]} />
</>
);
}
Parent Component:
...
const [bn, setBN] = useState("");
const childToParent = (childdata) => {
setBN(childdata);
console.log(childdata);
};
console.log("bn");
console.log(bn);
...
return (
...
<UppFormField
keyboardType="numeric"
autoCorrect={false}
// icon="bank"
name="acct_number"
placeholder="Account Number"
style={{ paddingRight: 50 }}
childToParent={childToParent}
/>
...
)
Make a middle function called
const onTextChange = (text) => {
setFieldValue(text)
parentFunction(text)
}
then TextInput takes has
onChangeText={onTextChange}

How to add comments to get stream in react native

I want to add a comment section to my react native app similar to instagram's one. I am using a getstream activity feed and have tried importing CommentField from react-native-activity-feed but i get an invariant violation error when i use it. However, i'm not fully convinced the CommentField will get me the type of comment section I want. Does getstream support this or will I need to make my own comment field and save it in a database?
EDIT:
I have this Activity:
const CustomActivity = (props) => {
return (
<Activity
{...props}
Footer={
<>
<CommentList
CommentItem={({ comment }) => ( <CommentItem comment={comment} /> )}
activityId={props.activity.id}
reactions={props.activity.latest_reactions}
/>
<Image source={ require('./images/logo.png') } style={{width:98, height:22}}/>
<LikeButton {...props} />
<CommentBox
onSubmit={(text) =>
props.onAddReaction('comment', CustomActivity, { text: text })
}
styles={{ container: { height: 78 } }}
/>
</>
}
/>
);
};
Then this gets rendered:
<FlatFeed
feedGroup = "timeline"
userID = User ID is put here
Activity={CustomActivity}
notify/>
I currently get this error when I submit a comment: Errors for fields 'activity_id', 'parent'
I think it may have something to do with activityId in the CommentList but im not too sure
You'll want to use the CommentBox and CommentList components. We do something like this in our example app:
<SinglePost
activity={activity}
feedGroup={feedGroup}
userId={userId}
Activity={(props) => (
<React.Fragment>
<Activity
{...props}
/>
<CommentList
CommentItem={({ comment }) => ( <CommentItem comment={comment} /> )}
activityId={props.activity.id}
reactions={props.activity.latest_reactions} />
</React.Fragment>
)}
Footer={(props) => {
return (
<CommentBox
onSubmit={(text) =>
props.onAddReaction('comment', activity, { text: text })
}
avatarProps={{
source: (userData) =>
userData.data.profileImage,
}}
styles={{ container: { height: 78 } }}
/>
);
}}
/>

React Native TextInput ref always undefined

I have a simple TextInput that I want to put a reference on in my render:
<View>
<TextInput ref={(component) => this._inputElement = component}>Input</TextInput>
{console.log(this._inputElement)}
<Button
onPress={this.addAddress}
title="Submit"
color="#841584"
/>
</View>
I want to then use that ref in a function above that is bound in my contructor:
constructor(props) {
super(props);
this.state = {
addresses: []
};
this.addAddress = this.addAddress.bind(this);
}
addAddress function:
addAddress(event, result) {
console.log("reference:", this._inputElement.value);
}
The console log in both the render and addAddress are always undefined.
I have looked around but no one seems to be having my problem, usually they have a typo or didn't bind the function they then want to call.
Why do I seem unable to have references?
Using State
Usually the way to use TextInput is to store the value in state.
Remember to initialize the address in your state as an empty string, otherwise having a null value for address could cause an error.
constructor(props) {
super(props)
this.state = {
....
address: ''
}
}
Then you could define your text input as follows
<TextInput
onChangeText={address => this.setState({address})}
value={this.state.address}
/>
Then in your addAddress
addAddress(event, result) {
console.log("reference:", this.state.address);
}
Using Refs
Alternatively you could use ._lastNativeText to access it from the reference
<TextInput
ref={ref => { this._inputElement = ref }}>
Input
</TextInput>
then in your addAddress
addAddress(event, result) {
// I always check to make sure that the ref exists
if (this._inputElement) {
console.log("reference:", this._inputElement._lastNativeText);
}
}
I wouldn't recommend the second method as you are accessing private methods that could be liable to change in a future release.
Textinput self-encloses
<View>
<TextInput ref={ref=> (this._inputElement = ref)}/>
<Button
onPress={this.addAddress}
title="Submit"
color="#841584"
/>
</View>
addAddress(event, result) {
console.log("reference:", this._inputElement._lastNativeText); //this get's the value, otherwise it's undefined
}
This snippet works properly in react native and react native web:
const txtRef = useRef(null)
return(
<TextInput
ref={txtRef}
onChangeText={text => txtRef.current.value = text}
/>
<Button
title='log and reset'
onPress={() => {
console.log(txtRef.current.value)
txtRef.current.clear()
txtRef.current.value = ''
}}
/>
)
`

React Native + Redux Form : Wizard Form handleSubmit

I am trying to create wizard form in react native with the help of this example. but handleSubmit is not working.
Signup.js
submitForm(values){
console.log("formValues",values);
}
nextPage(){
this.setState({ page: this.state.page + 1 });
}
render(){
const { page } = this.state;
{page === 1 && <WizardFormFirstPage nextPage={this.nextPage} />}
{page === 2 && <WizardFormSecondPage nextPage={this.nextPage} />}
{page === 3 && <WizardFormThirdPage onSubmit={this.submitForm} />}
}
WizardFormFirstPage and WizardFormSecondPage works fine. but when it comes on WizardFormThirdPage it doesn't do anything (I can't see any console log in my terminal for validations and submitForm function). here is the code written.
WizardFormThirdPage.js
const WizardFormThirdPage = props => {
const { handleSubmit, onSubmit } = props;
return (
<View>
<Field name="street" component={InputField} label="Street" />
<Button style= {{ margin: 10 }} block primary onPress={handleSubmit(onSubmit)}>
<Text>Continue</Text>
</Button>
</View>
);
};
export default reduxForm({
form: 'signup', // <------ same form name
destroyOnUnmount: false, // <------ preserve form data
forceUnregisterOnUnmount: true, // <------ unregister fields on unmount
validate,
})(WizardFormThirdPage);
This is probably too late but I figured out what I was doing wrong.
While wrapping the react native InputText component with the redux form Field component. We have to pass props to the InputText component. I was passing props like this ...
<InputText {...props} />
The {...props} attaches all the event handlers like onChange, onSubmit, etc to the component so we don't have to do it manually. The issue lies here, that the InputText component has a onChangeText property rather than onChange which redux form injects into the props.
The correct way to do this is ..
const renderInput = ({ input: { onChange, ...restInput }}) => {
return <TextInput style={styles.input} onChangeText={onChange} {...restInput} />
}
const Form = props => {
const { handleSubmit } = props
return (
<View style={styles.container}>
<Text>Email:</Text>
<Field name="email" component={renderInput} />
<TouchableOpacity onPress={handleSubmit(submit)}>
<Text style={styles.button}>Submit</Text>
</TouchableOpacity>
</View>
)
}
This answer came from the article Simple React Native forms with redux-form.