setNativeProps on Button Component - react-native

When I define a button in React Native as:
<Button ref="buttonRef" title="Button" onPress={this.buttonPressed}/>
And its onPress function as:
buttonPressed(){
this.refs.buttonRef.setNativeProps({color:"#ffffff"});
}
I get the following error:
this.refs.buttonRef.setNativeProps is not a function. (In
'this.refs.buttonRef.setNativeProps({
color: "#ffffff"
})', 'this.refs.buttonRef.setNativeProps' is undefined)
However, if I were to define any other type of component, e.g. text input as
<TextInput ref="userInputRef" value={"this is text"} />
With the function changing its props:
buttonPressed(){
this.refs.textRef.setNativeProps({color:"#ffffff"});
}
Everything changes correctly.
Is there a reason that the button component is unable to have its native props set through setNativeProps?

Button component is a simple custom component created from Touchable components and it doesn't have a ref property. You can check the source code of Button component here.
If you need to change properties of a component you should use state values for that.
Sample
buttonPressed = () => {
this.setState({color:"#ffffff"});
}
//....
<Button ref="buttonRef" color={this.state.color} title="Button" onPress={this.buttonPressed}/>

Related

How can I close a Popover programatically with native base?

I am using Native Base Popover.
scenario
As a user,
I can press on the list,
So that I can select a fruit
My problem is I don't understand how to close the <Popover /> from the outside of the component.
Here is my organization
<Formik>
<Popover>
<FlatList>
<Pressable onPress={() => handlePress(item.id)} /> //Banaba
<Pressable onPress={() => handlePress(item.id)} /> //Potato
<Pressable onPress={() => handlePress(item.id)} /> //Ananas
NativeBase offers a useDisclose() hook for handling opening/closing of modals and other popup windows.
That hook provides an isOpen state (as #mainak's answer mentions) as well as onOpen() and onClose() functions to manipulate that state. You can pass these helpers as arguments as-needed into the props of the same name within the Popover component to handle open/close state.
Optionally, you can in addition pass true or false into useDisclose() to override the starting value of isOpen (defaults to false).
Here is an example below for reference.
import React from "react";
import { Popover, useDisclose } from "native-base";
function MyComponent() {
const { isOpen, onClose, onOpen } = useDisclose()
return (
<>
<Button onPress={onOpen}>Open the Popover</Button>
<Popover isOpen={isOpen} onClose={onClose}>
<Popover.Content>
<Popover.Arrow />
<Popover.CloseButton />
<Popover.Header>My Popover Title</Popover.Header>
<Popover.Body>You can place the content of your popover inside the body.</Popover.Body>
<Popover.Footer>
<Button onPress={onClose} variant="ghost">Cancel</Button>
</Popover.Footer>
</Popover.Content>
</Popover>
</>
)
}
can you try isOpen prop in Popover tag and have it as a state value like
const [isOpen, setOpen] = React.useState(true);
...
<Formik>
<Popover isOpen={isOpen}>
<FlatList>
...

Change SVG component on press with React Native

Background
Pretty simple question: I want to create a "like" button in RN. To do this I have to separate components which are SVG files. One is just the outline of a heart, the other one is filled.
The screen in which I'm trying to build this button is a Function component so I should use hooks. I know about state but don't know how to properly use it.
What I need
A Touchable Opacity component which holds an onPress method which changes the image component when pressed.
Thanks a lot in advance!
import React ,{useState} from 'react';
import {TouchableOpacity } from "react-native";
export default function Like() {
const [isLiked,setIsLiked]=useState(false) ;
const handleLikePress=()=>{
setIsLiked(!isLiked)
}
return (
<TouchableOpacity onPress={handleLikePress}>
{isLiked? <FilledHeartSVG/>: <OutlineHeartSVG/> }
</TouchableOpacity>
)
}
by default, we are showing an outline of a heart SVG
when press event trigger we are changing isLiked state value
if isLiked is true then show filled heart SVG
if isLiked is false then show outline of a heart SVG
FilledHeartSVG and OutlineHeartSVG is just example use your SVG there
You can do something like below, here i have made a toggle for the text but you can change it to your image component, also the callback prop can be used if you want to use that outside the LikeButton
const LikeButton = ({callback}) => {
const [liked, setLiked] = React.useState(false);
return (
<TouchableOpacity onPress={()=>{
setLiked(!liked);
if(callback)
{
callback();
}
}}>
<Text>{liked?"Liked":"Like"}</Text>
</TouchableOpacity>
);
};
You can tryout this snack which uses icons
https://snack.expo.io/#guruparan/likebutton

React-native child component not updating when parent state updates

I have a parent component which holds a child component. The parent is getting its data from redux. The object in store looks something like the below:
//object in redux store
object :[{
item: {
name: 'item'1,
selected: false
},
item:{
name: 'item'1,
selected: false
}
}]
My Parent component contains a FlatList which renders the child component:
//parent component
<FlatList
data={this.props.object}
renderItem={( object ) => <Object object={object.item} />}
keyExtractor={object => object.id}
/>
My child component contains a button, which toggles the selected property of each item. The desired behavior is that the style of the button changes based on the value if the selected property. My child button component looks something like the below:
// child component
render(){
return (
<View>
<Text>{this.props.name}</Text>
<Button
title="toggle"
buttonStyle={{backgroundColor: this.props.selected? 'red' : 'green'}}
onPress={() => handling toggle by changing state in store, it works fine and
console.logs correctly}/>
</View>
);
}
After the button is toggled, the state of the object does change, and console.logs correctly, however the style of the button only updated when i go out and back into the page as if the child component is not updating.
How can i get the button style to update directly on button toggle? Thanks
More information would help, but my initial thoughts are that the toggled state might not be causing the FlatList component to pick up the changes, in order to trigger a re-render.
This can be resolved by the optional extraData prop that can be passed into your FlatList component
https://reactnative.dev/docs/flatlist#extradata
it turns out the changes I was doing in my reducer did not trigger a component update due to the shallow equality comparison redux performs.
I fixed by returning this in my reducers
let obj = {...}
return { ...state, object: {...state.object}
instead of
let obj = {...}
return {...state, object: obj }

How do I bind a local function when I pass a rendered view interacting with that function to a prop in react-native?

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

setState() adds a Proxy object to property instead of string value in react native

This is a very weird problem and I'm sure I'm overlooking something very simple.
When I load a new component AddNewCategory, I initially set a an empty string to a text property on this.state. Logging on console shows the text value as empty too.
I update this value using onChange of Button component. I know that the text property is so far updating as expected because the value of the input field changes accordingly.
<Button onChange={text=>this.setState({})}>
But when I try to retrieve the value of text property, I see that instead of a string, the text is now assigned a Proxy object.
I'm only trying to get the value of the input field so I can pass the value on to an action creator.
Here's the entire code,
import React from 'react';
import { View, Text, TextInput, Button} from 'react-native';
class AddNewCategory extends React.Component {
constructor(props) {
super(props)
this.state={
text: ''
};
console.log('after initialising constructor');
console.log(this.state);
this.onContinueButtonPress = this.onContinueButtonPress.bind(this);
}
onContinueButtonPress() {
console.log('after onContinueButtonPress');
console.log(this.state);
this.props.addNewCategory('Random Value');
}
render(){
return(
<View>
<Text>Name your new task list</Text>
<TextInput
placeholder="Things to do today.."
value={this.state.text}
onChange={(text)=>this.setState({text: text})}
/>
<Button
title={'Continue'}
onPress={this.onContinueButtonPress}
/>
</View>
);
}
};
export default AddNewCategory;
I have no idea why you are giving an onChange prop to a Button component.
Anyway, for a TextInput, you should give the onChangeText property.
<TextInput onChangeText={text => this.setState({ text })}
Other properties have been omitted.
Using just onChange is like handling the usual onChange event when doing web development, where the first parameter to the callback method only gives the event; to get the actual input value you have to say event.target.value.
onChange={(event) => console.log(event.target.value)}