The following is a first attempt at learning to simply change the style of an element onPress in react native. Being well versed in web languages I am finding it difficult as it is not as straight forward.
For reasons as yet unknown, the element requires two clicks in order to execute.
export class NavTabItem extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false
}
this.NavTabAction = this.NavTabAction.bind(this)
}
NavTabAction = (elem) => {
elem.setState({active: !elem.state.active})
}
render() {
return (
<TouchableOpacity
style={this.state.active ? styles.NavTabItemSelected : styles.NavTabItem}
onPress={()=> {
this.NavTabAction(this)
}}>
<View style={styles.NavTabIcon} />
<Text style={styles.NavTabLabel}>{this.props.children}</Text>
</TouchableOpacity>
);
}
}
Other issues:
I also have not worked out how a means of setting the active state to false for other elements under the parent on click.
Additionally, Is there a simple way to affect the style of child elements like with the web. At the moment I cannot see a means of a parent style affecting a child element through selectors like you can with CSS
eg. a stylesheet that read NavTabItemSelected Text :{ // active style for <Text> }
Instead of calling elem.setState or elem.state, it should be this.setState and elem.state.
NavTabAction = (elem) => {
this.setState(prev => ({...prev, active: !prev.active}))
}
And instead of passing this in the onPress, you should just pass the function's reference.
onPress={this.NavTabAction}>
You should also remove this line because you are using arrow function
// no need to bind when using arrow functions
this.NavTabAction = this.NavTabAction.bind(this)
Additionally, Is there a simple way to affect the style of child elements like with the web
You could check styled-component, but I think that feature don't exists yet for react native. What you should do is pass props down to child components.
Thanks to everyone for their help with this and sorting out some other bits and pieces with the code.
The issue in question however was that the style was changing on the second click. A few hours later and I have a cause and a solution for anyone suffering from this. Should any of the far more experienced people who have answered this question believe this answer is incorrect or they have a better one, please post it but for now here is the only way I have found to fix it.
The cause:
Using setState was correctly re rendering the variables. This could both be seen in the console via console.log() and directly outputted in the render making them visible.
However, no matter what was tried, this did not update the style. Whether it was a style name from the Stylesheet or inline styles, they would update on the second click rather than the first but still to the parameters of the first. So if the first click should make a button turn from red to green, it would not do so even though the new state had rendered. However if a subsequent click should have turned the button back to red then the button would now go green (like it should have for the first click). It would then go red on the third click seemingly always one step behind the status passed to it.
Solution
To fix this, take the style off the the primary element (forgive terminology, someone edit), in my case, the TouchableOpacity element. Add in a child View element and place the styles on that View element instead along with the ternary operator and wallah.
It seems any change to status on the effective master element or container if you prefer, only takes affect after another render, not that contained in setStatus.
Final code:
export class NavTabItem extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false
}
}
NavTabAction = () => {
this.setState({active: !this.state.active})
}
render() {
this.state.active == true ? console.log("selected") : console.log("unselected")
return (
<TouchableOpacity onPress={this.NavTabAction}>
// added View containing style and ternary operator
<View style={this.state.active == true ? styles.NavTabItemSelected : styles.NavTabItem}>
<View style={styles.NavTabIcon} />
<TextCap11 style={styles.NavTabLabel}>{this.props.children}</TextCap11>
</View>
// End added view
</TouchableOpacity>
);
}
}
Related
I'm using react-native-swipe-list-view (https://github.com/jemise111/react-native-swipe-list-view) in my React Native app and I'm trying to close rows programmatically.
Once the user swipes to the right or left and clicks the button there, I call a function to make API calls and handle a few things. This is where I also try to close the row programmatically. This is working ONLY for the last item in the list. Anything above it, the row stays open.
I do hit my handleClickUpdateItemStatus() function and the API call works fine but as I said, only the last item in the list will close. Anything above that one stays open even though all the other code in the function work fine.
My code looks like this:
class MyComponent extends Component {
constructor(props) {
super(props);
this.handleClickUpdateItemStatus = this.handleClickUpdateItemStatus.bind(this);
}
handleClickUpdateItemStatus(itemId, value) {
this._swipeListView.safeCloseOpenRow();
// Call my API to update item status
}
render() {
return(
<Container>
<SwipeListView
ref={ref => this._swipeListView = ref}
data={this.props.items}
... // Omitted for brevity />
</Container>
);
}
}
Any idea what's causing this?
I have multiple buttons in a screen and all are independent like one button is for navigating to next page, another one is for a popup calendar, etc. When I click quickly on all these buttons, all clicks are triggered and I tried using disabling the buttons by using a boolean state variable. But still I can click on the button within the time I set the state. So is there any way to prevent this to happen?
Thanks in Advance!
You can easily achieve this behavior by using setState method. However be careful, as set state is asynchronous. For simple scenario you can to do it like this:
constructor(props) {
super(props);
this.state = {
enableButton: false
};
}
And then use your button or TouchableOpacity like this:
<TouchableOpacity
disabled={this.state.enableButton}
onPress={() => handleMe()}>
<Text>
{text}
</Text>
</TouchableOpacity>
And then for enabling your button:
handleMe() {
this.setState({
enableButton: true
});
}
Let me know, if you are still confused.
There might be a issue with function binding. The function might not have been binded which makes them being called even without tap.
I have a screen that contains many of the same CustomSlider component. I would like to retrieve the slider values from every slider.
What is best practice for doing this in react native?
Here's a minimum working example, with 3 sliders:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import MultiSlider from "#ptomasroos/react-native-multi-slider";
class CustomSlider extends Component {
constructor(props) {
super(props)
this.state = {
multiSliderValue: [1, 9]
}
}
multiSliderValuesChange = values => {
this.setState({multiSliderValue: values});
};
render(){
return (
<MultiSlider
values={this.state.multiSliderValue}
onValuesChange={this.multiSliderValuesChange}
min={0}
max={10}
step={1}
/>
)
}
}
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
};
}
get_slider_values = () => {
// what is best practice to access the values of every slider here?
// eg an object like this
const slider_values = [[1.4, 7.4], [4.3, 7.0], [1.9, 3.2]]
return slider_values
}
render() {
return (
<View style={{alignItems: 'center', justifyContent: 'center', padding: 50}}>
<CustomSlider />
<CustomSlider />
<CustomSlider />
<Text>{`The slider values are: ` + JSON.stringify(this.get_slider_values())}</Text>
</View>
);
}
}
There is no need for a complex solution. The way that I would handle this is to manage the state in the parent component. The CustomSlider doesn't really need to know its state. As the parent component needs to know the state of the sliders it is better to handle it there.
So as the parent component is going to handle the state this means we need to make some changes to what you are doing.
Set initial values in the parent component for the state of each of the sliders. This is important, it makes it means that even if the user doesn't touch the sliders we know the values of them.
Pass a function to each of the sliders that calls back to the parent component.
As the parent component is controlling the state we can remove the state from the CustomSlider. This gives a few options we could leave it as a Component, change it to a PureComponent or go one step further an change it to a Functional Component If the slider doesn't really need to know its state then the last option should be best for performance.
Here is how I would refactor your App.js
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
sliderValues: [[1, 9],[1, 9],[1, 9]] // we should control the state here
};
}
// this uses function currying to bind the function and pass a value to it
onChange = (index) => (values) => {
this.setState( prevState => {
let sliderValues = prevState.sliderValues;
sliderValues[index] = values;
return {
sliderValues
}
})
}
render() {
return (
<View style={{alignItems: 'center', justifyContent: 'center', padding: 50}}>
<CustomSlider intialValues={this.state.sliderValues[0]} onChange={this.onChange(0)}/>
<CustomSlider intialValues={this.state.sliderValues[1]} onChange={this.onChange(1)}/>
<CustomSlider intialValues={this.state.sliderValues[2]} onChange={this.onChange(2)}/>
<Text>{`The slider values are: ` + JSON.stringify(this.state.sliderValues)}</Text>
</View>
);
}
}
Notice how we don't actually need a function to get the values of the sliders as they are stored in state. That means we can access the sliders' values directly by using this.state.sliderValues.
Here is your CustomComponent refactored to work with the above code:
class CustomSlider extends Component { // this could easily be swapped for a PureComponent
render(){
return (
<MultiSlider
values={this.props.intialValues}
onValuesChange={this.props.onChange}
min={0}
max={10}
step={1}
/>
)
}
Notice how it doesn't need to manage state at all as the parent component is handling it. It also means that we can remove a lot of code that isn't actually necessary. This is why I think we can go one step further and make it a Functional Component
const CustomSlider = ({intialValues, onChange}) => {
return (
<MultiSlider
values={intialValues}
onValuesChange={onChange}
min={0}
max={10}
step={1}
/>
)
}
If however if the CustomSlider needs to know its state because it is doing something more than capturing the values of the slider then you can easily add state to it by using it as a Component or a PureComponent.
Snack
Here is a snack showing the above code working. I have shown all three possible components and have used them in the App.js. There isn't much difference in how they look, but your use case will determine which one that you use. https://snack.expo.io/#andypandy/multisliders
Best Practice
The best practice is to go for the simplest solution that you can find. Ideally that would be a Functional Component, then a PureComponent, and finally a Component. It is also important to think about where and how the state is going to be used. Some questions that I ask myself are:
Does a component really need to know its own state?
Where do I plan on using that state?
How long do I need these state values for?
Do I need to persist that state?
What tools are available to me based on what I am currently using?
Do I really need to add another dependency or more to make this work?
If you need the values from the sliders in multiple places in your app you can use some of the features that are provided by react-native or your navigation to pass these values around. Redux and MobX are big overheads in terms of complexity and should only really be used if you need a global state management system, for the majority of cases they can be avoided.
You can store the state dynamically by some key given to each child, and access each ones state by the key you give it.
One way is to pass a closure from parent component to CustomSliders as props and monitor the changes.
<CustomSlider idx={n}
theClosurePassedThrough= (n, values) => {
// update the parents states here accordingly
}
>
Then call this closure at appropriate time.
multiSliderValuesChange = values => {
this.setState({multiSliderValue: values});
this.props.theClosurePassedThrough(this.props.idx, values);
};
The best practice, though, is to use MobX or Redux.
Hi I am looking for the solution to change text dynamically.
I am writing code to show processing results on screen.
After some googling, I found there is a code to update text dynamically as follows.
But I would like to update text without any internal event. I want to change text from outside of the class. But I don't know how to implement it as I am a javascript and react-native beginner. There are other classes to process some functions so that I need to show the updated results using Results class which is an another component of the screen.
How can I deliver 'result' to Results class and how to update it dynamically and automatically?
class Results extends Component {
constructor() {
super()
this.state = {
log: 'Processing results'
}
}
updateText = (result) => {
this.setState({log: result})
}
render() {
return (
<View>
<Text onPress = {this.updateText}>
{this.state.log}
</Text>
</View>
)
}
}
This sounds to me that props can solve your problem.
Basically when you try to render Results class, pass along the value as a prop like below:
<Results dynamicText='HI' />
Then, from your Results class, access this external value via this.props.dynamicText as below
class Results extends Component {
render() {
return (
<View>
<Text>
{this.props.dynamicText}
</Text>
</View>
)
}
}
In addition to what #Issac answered, you can also hook up your current class to Redux and dispatch actions from another class to force state changes.
React Native and ReactJS has a different concept of how classes react to each other. Most other languages use inheritance based interactions to affect changes in classes other than itself. React itself is more composition based where changing the value/state/variable of one class requires either a state change or a prop change. The caveat to that us using Redux, which utilizes an overarching Store where any component that's connected to it can pull values or dispatch actions to change values.
I am trying to create a button which is displaying and hiding a navigation menu on click. I am using Redux to get the current state into the Component, but something is not working with the onPress function.
When pressing the button I want to check the current state of this.state.showNavigation (can be true/false) but I am getting an "undefined is not an object" error immediately after clicking the button.
I think I am running into a lifecycle issue here. I already tried to ship around this via setting the state in componentWillMount like that:
componentWillUpdate(){
this.state = NavigationStore.getState();
}
Anyway that didn't help. Some advise is much appreciated. Thanks!
Heres my code:
class NavigationButton extends React.Component {
constructor(props, context) {
super(props, context);
this.state = NavigationStore.getState();
NavigationStore.subscribe(() => {
this.setState(NavigationStore.getState());
});
// alert(this.state.showNavigation);
}
render() {
return (
<TouchableOpacity
onPress={this.handlePressButton}
style={navigationButtonStyles.button}>
<Image source={buttonImage} />
</TouchableOpacity>
);
}
handlePressButton() {
if(this.state.showNavigation){
NavigationStore.dispatch({
type: 'HIDE_NAVIGATION',
});
}
else{
NavigationStore.dispatch({
type: 'SHOW_NAVIGATION',
});
}
}
};
I was using a pretty strange approach, I did not use the react-redux package for the whole thing and couldn't connect my store. I deep dived into https://github.com/bartonhammond/snowflake and got it solved, the snowflake example was really helpful to understand the basics!