0

I want to display a component(say, a View or Text component) in my current screen only if I return back to this screen from some other screen.

For e.g, say I am at the Home.js where I am displaying the view components. The count of this view components depends upon the number of times one goes(or visits) the Break.js screen. Like If i have visited the Break.js screen thrice, then there should be 3 View components available at the Home.js screen.

I am a beginner in React-Native, so don't have any idea how to implement this....I have gone through the similar query like Dynamically rendering components - React Native and React Native View Render

but couldn't understand anything. Pls help as I have nothing to show what I have tried so far.....

1 Answer 1

1

Below is one way of updating your component, where you update the viewCount before navigating to the other screen. This works only if the previous screen exists in the memory after navigation like in the cases of stack navigators. This is a basic idea which u can modify for your use case.

class HomeScreen extends Component {

  onNavigate() {
    this.updateViewCount();
    // ... navigate to BreakScreen
  }

  updateViewCount() {
    this.setState({numOfViews: this.state.numOfViews + 1});
  }

  render() {
    // Create an array and push your elements based on count
    // this.state.numOfViews manages the count
    let views = [];
    for(let i = 0; i <= this.state.numOfViews; i++) {
      views.push(<SomeComponent />);
    }

    // Render your custom views
    return(
      <View>
       {views}
       <Button onPress={() => this.onNavigate()} />
      </View>
    );
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think it will work....will confirm after trying this.....Thanks a ton for this...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.