Here is a simplified version of my code.
Notice the setFieldValue_ and this.setFieldValue_ = setFieldValue;
This code works fine, I'm able to get the output when submit button is clicked.
I'm actually wondering if this is the right way to do it? If not, can you point me to the right direction? Also what is this method called? (assigning class variable to some function and use it within another function)
class MyComponent extends React.Component {
setFieldValue_;
someFunction() {
this.setFieldValue_("name", value);
}
render() {
return (
<Formik
initialValues={{
something: ""
}}
onSubmit={values => console.log(values)}
>
{({
setFieldValue,
}) => {
this.setFieldValue_ = setFieldValue;
<ThirdPartyCustomComponent onChange={this.someFunction} />
}}
</Formik>
}
}
I would personally have the onChange simply call formik set field value there and then rather than using different functions. Strictly speaking you don't want to set the value like that because every re-render is setting the value again.
I would also recommend looking at custom formik inputs using the useField hook - https://jaredpalmer.com/formik/docs/api/useField. This will allow you to write a small wrapper around your third party component and formik. Noticing you have used a class based component you may want to do some short reading into react hooks before throwing yourself into using useField.
Docs example:
const MyTextField = ({ label, ...props }) => {
const [field, meta, helpers] = useField(props);
return (
<>
<label>
{label}
<input {...field} {...props} />
</label>
{meta.touched && meta.error ? (
<div className='error'>{meta.error}</div>
) : null}
</>
);
};
Related
I'm passing a render to the Accordion element in native-base using the renderContent prop. The render contains two buttons, which, when pressed, run functions that are local to the current component. Unfortunately those functions are not available once it has been actually rendered.
How do I bind the functions properly so that when pressed, the correct functions are referenced?
I'm using the most modern stable releases of react-native, native-base, and I'm running this through expo for testing.
Here's the documentation on native-base:
http://docs.nativebase.io/Components.html#accordion-custom-header-content-headref
Accordion:
<Accordion
dataArray={ this.state.websites }
renderContent={ this._renderAccordionContent }
/>
renderContent:
_renderAccordionContent(content) {
return (
<Button
onPress={() => this.openSite(content.path)}
>
<Text>Open</Text>
</Button>
<Button
onPress={() => this.editSite(content.key)}
>
<Text>Edit</Text>
</Button>
)
}
When the buttons are pressed, the expected results are that the functions are run.
The actual results are that when the buttons are pressed, these errors are populated:
_this2.openSite is not a function.
_this2.editSite is not a function.
Thank you for any help.
Check out this excellent article that shows several different ways of binding your functions https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56
Here is an example of binding it in the constructor of your component that uses the Accordion component. It is by no means the only way of binding the functions. The above article gives 5 different ways of doing it.
class MyComponent extends Component {
constructor(props) {
super(props);
this.openSite = this.openSite.bind(this);
this.editSite = this.editSite.bind(this);
}
// I am assuming you have written your functions like this and not as arrow functions
openSite (path) {
...
}
editSite (key) {
...
}
_renderAccordionContent(content) {
return (
<Button
onPress={() => this.openSite(content.path)}
>
<Text>Open</Text>
</Button>
<Button
onPress={() => this.editSite(content.key)}
>
<Text>Edit</Text>
</Button>
)
}
render() {
...
<Accordion
dataArray={ this.state.websites }
renderContent={ this._renderAccordionContent }
/>
...
}
}
I'd like to have a context menu triggered on long press different places using React Native.
I.e. in a dialer like the default dailer. You can long-click on any contact and get a 'copy number' menu. And also you can long-click on the name of the person once you've opened their 'contact card'.
The straight-forward way needs a lot of copy-pasted boilerplate, both components and handlers.
Is there a better pattern for doing this?
All Touchable components (TouchableWithoutFeedback, TouchableOpacity etc.) has a property called onLongPress. You can use this prop to listen for long presses and then show the context menu.
To eliminate code mess and doing lots of copy paste you can separate your context menu as a different component and call it when the long press happen. You can also use an ActionSheet library to show the desired options. React native has a native API for iOS called ActionSheetIOS. If you get a little bit more experience in react and react-native you can create a better logic for this but I'm going to try to give you an example below.
// file/that/contains/globally/used/functions.js
const openContextMenu = (event, user, callback) => {
ActionSheetIOS.showActionSheetWithOptions({
options: ['Copy Username', 'Call User', 'Add to favorites', 'Cancel'],
cancelButtonIndex: [3],
title: 'Hey',
message : 'What do you want to do now?'
}, (buttonIndexThatSelected) => {
// Do something with result
if(callback && typeof callback === 'function') callback();
});
};
export openContextMenu;
import { openContextMenu } from './file/that/contains/globally/used/functions';
export default class UserCard extends React.Component {
render() {
const { userObject } = this.props;
return(
<TouchableWithoutFeedback onLongPress={(event) => openContextMenu(event, userObject, () => console.log('Done')}>
<TouchableWithoutFeedback onLongPress={(event) => openContextMenu(event, userObject, () => console.log('Done'))}>
<Text>{userObject.name}</Text>
<Image source={{uri: userObject.profilePic }} />
</TouchableWithoutFeedback>
</TouchableWithoutFeedback>
);
}
}
Similarly as the previous answer combine onLongPress with imperative control for popup menu - something like
<TouchableWithoutFeedback onLongPress={()=>this.menu.open()}>
<View style={styles.card}>
<Text>My first contact name</Text>
<Menu ref={c => (this.menu = c)}>
<MenuTrigger text="..." />
<MenuOptions>
// ...
</MenuOptions>
</Menu>
</View>
</TouchableWithoutFeedback>
When it comes to a lot of boilerplate - in React you can do your own components that you can reuse everywhere thus reducing boilerplate (and copy&paste)
See full example on https://snack.expo.io/rJ5LBM-TZ
I'm a new to react-native and i need a help. I want to do this: I have a button, when click it, a list item will show under the button. Help me guys !
Thanks
I suggest you to use or learn (if you want make your own popover) from react-native-list-popover. Here some screenshot from reace-native-list-popover:
Make a Boolean flag in your component state and initiate it with false and then use it for showing the list. You can use FlatList for make a good list.
The example code can be like this:
export default class ClassName extends Component {
state = {showList: false}
_onPress = () => {
this.setState({showList: true})
}
render() {
return (
<View>
<Button onPress={this._onPress}>Show List</Button>
{(this.state.showList) && <FlatList
data={[{key: 'a'}, {key: 'b'}]}
renderItem={({item}) => <Text>{item.key}</Text>}
/>}
</View>
)
}
}
I'm using Redux Form (RF) in a React Native application. Everything works fine but I can not figure out how to get the refs from the Field input to go to the next input field with Redux Form.
Without RF this solution would work just fine.
Here is my code:
class RenderInput extends Component {
const { input, nextField, refs,
meta: { touched, error, warning },
input: { onChange } } = this.props
render() {
return (
<Input
returnKeyType = {'next'}
onChangeText={onChange}
onBlur={input.onBlur}
onFocus={input.onFocus}
onSubmitEditing = {(event) => {
// refs is undefined
refs[nextField].focus()
}}/>
)
}
}
class Form extends Component {
render() {
return (
<Field
name="field1"
focus
withRef
ref='field1'
nextField = "field2"
component={RenderInput}/>
<Field
name="vendor"
withRef
ref="field2"
nextAction = "field3"
component={RenderInput}/>
)
}
}
I'm passing on the property nextField to the component to determine the next input field when the Next key on the keyboard is clicked but I can not get the refs property inside the RenderInput component.
Any idea how to get the refs property?
This solution passes props from the Form component to the RenderInput component and passes a function call back.
Here's the code:
class RenderInput extends Component {
const { input, refField, onEnter,
meta: { touched, error, warning },
input: { onChange } } = this.props
render() {
return (
<TextInput
ref = {refField}
returnKeyType = {'next'}
onChangeText={onChange}
onBlur={input.onBlur}
onFocus={input.onFocus}
onSubmitEditing={onEnter}/>
)
}
}
class Form extends Component {
render() {
return (
<Field
name="field1"
focus
withRef
ref={(componentRef) => this.field1 = componentRef}
refField="field1"
component={RenderInput}
onEnter={() => {
this.field2.getRenderedComponent().refs.field2.focus()
}}/>
<Field
name="field2"
withRef
ref={(componentRef) => this.field2 = componentRef}
refField="field2"
component={RenderInput}/>
)
}
}
So what happened here?
I assign the ref to local scope with ref={(componentRef) => this.field1 = componentRef} as #Ksyqo suggested. Thanks for the hint.
I pass refField="field1" to the RenderInput and assign the value to the input ref property ref = {refField}. This will add the input object to the refs property.
I assigned a onEnter function in the Field
I pass the function to the props of RenderInput and assign it to the onSubmitEditing={onEnter} function. Now we have bind the two functions together. That means if onSubmitEditing gets invoked the onEnter function gets invoked as well
Finally, refer to the local field field2, get the rendered Component and use the refs, which we assigned in the Input field, to set the focus. this.field2.getRenderedComponent().refs.field2.focus()
I don't know if this is the most elegant solution but it works.
For people who are using Redux Form + React Native Elements, just follow #Thomas Dittmar answer, and add the following prop to the 'FormInput' component: textInputRef={refField}
The newest version of React Native Element has added the focus() method, so you don't have to worry about that.
withRef is deprecated, use forwardRef instead.
I worked on getting a ref like this that worked for me.
const renderComp = ({
refName,
meta: { touched, error },
input,
...custom
}) => (
<MyComponent
ref={refName}
{...custom}
/>
)
<Field
name={name}
component={renderComp}
ref={node =>
isLeft ? (this.compRef1 = node) : (this.compRef2 = node)}
refName={node =>
(this.myRef= node) }
withRef
/>
now access instance functions like this.
this.myRef.anyFunc()
I had a slightly different use case, but I imagine it works for the above as well.
I used the focus action
import { focus } from 'redux-form';
dispatch(focus('signIn', 'email'));
Then in the (custom) form field that contains the TextInput, I added in the render function
<TextInput
ref="email"
/>
formStates.filter((state) => meta[state]).map((state) => {
if(state === 'active'){
this.refs.email.focus()
}
})
No worries about the component nesting/hierarchy anymore.
From what I have read its best to try and structure react apps with as many components as "dumb" renderers. You have your containers which fetch the data and pass it down to the components as props.
That works nicely until you want to pass functions down the chain that require arguments other than events.
class MyClass extends Component {
_onItemPress (myId) {
// do something using myId
}
render () {
return <MyComponent myID={10} onPress={(myId) => this._onItemPress(myId)} />
}
}
If I simply pass that as my onPress handler to MyComponent it won't return myId when called. To get around this I end up doing something like this.
export default ({myId, onPress) => {
const pressProxy = () => {
onPress(myId)
}
return (
<TouchableHighlight onPress={pressProxy}>
<Text>Click me to trigger function</Text>
</TouchableHighlight>
)
}
Am I doing this completely incorrectly? I would like to be able to have a simple component that I can re-use for list items where its sole function is to take a title, onpress function and return a list item to be used in ListViews renderRow function. Many of the onPress functions will require variables to be used in the onPress however.
Is there a better way?
The proper syntax would be something like this:
render () {
let myId = 10;
return <MyComponent myID={myId} onPress={() => this._onItemPress(myId)} />
}
Also, if you plan to use this inside _onItemPress (for example to call other methods in MyClass), you need to bind the scope like this:
render () {
let myId = 10;
return <MyComponent
myID={myId}
onPress={() => this._onItemPress(myId).bind(this)} />
}
...or you can bind it already in the constructor if you prefer:
constructor(props) {
super(props);
this._onItemPress = this._onItemPress.bind(this);
}
You did it correctly.
MyComponent is as "dumb" as it should be: it does not care about the source of its props, it acts independently from higher level of logic of the app and it can be reused somewhere else in the app.
Some improvements you can work on:
MyComponent does not need myId itself. Exclude it from the component and let parental component deals with related logics to id
Provide a safe check for props onPress. If you want to reuse MyComponent somewhere, it is better to check for existence of onPress property before calling it, or provide a default value for onPress in case developer adds in unwanted props types.
Example of MyComponent
class MyComponent extends Component {
handlePress = (e) => {
if (typeof this.props.onPress === 'function') {
this.props.onPress()
}
}
render() {
return (
<TouchableHighlight onPress={this.handlePress}>
<Text>Click me to trigger function</Text>
</TouchableHighlight>
)
}
}
and to call MyComponent in MyClass:
class MyClass extends Component {
_onItemPress(myId) {
}
render () {
return <MyComponent onPress={() => this._onItemPress(10)} />
}
}