Changing the value of a variable in React Native does not reflect in the child component when passed as props

Hey there, I'm facing a bit of a dilemma with this problem. The issue is that I can't use state within navigationOptions. Here's what I've attempted:

I initialized my variable

let isFilterVisible: boolean = false;

In the navigationOptions block, I'm calling a function in the onPress event.

static navigationOptions = ({ navigation }: NavigationInjectedProps) => ({
    headerRight: (
            <FilterButton onPress={() => {Installations.handleFilterVisibility(isfilterVisibile)}}/>
   ),
});

A simple static function where I manipulate the value

static handleFilterVisibility(filterVisibility: boolean){
    isfilterVisibile = !filterVisibility;
}

Then it's passed down to the child component as props

<Filter isFilterVisible={isfilterVisibile}/>

Everything appears to be set up correctly, but when I try to log the props in the child component.

ComponentDidUpdate and ComponentWillReceiveProps do not display any logs.

Any thoughts on where I might have gone wrong?

Answer №1

After much trial and error, I finally cracked the code with the help of navigation params. Here's the solution that worked for me:

static navigationOptions = ({ navigation }: NavigationInjectedProps) => ({
    headerRight: (
            <FilterButton onPress={() => {
                const {params = {}} = navigation.state;
                params.handleFilterVisibility()
            }}/>
    ),
});

handleFilterVisibility = () => {
    const { isFilterVisible } = this.state;
    const { navigation } = this.props;
    this.setState({isFilterVisible: !isFilterVisible}, () => {
        navigation.setParams({ 
            isFilterVisible
        });
    })
}

componentDidMount() {
    const { navigation } = this.props;
    const { isFilterVisible } = this.state;
    navigation.setParams({
        handleFilterVisibility: this.handleFilterVisibility,
        isFilterVisible
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which tool would be better for starting a new Angular project: angular-seed or yeoman?

I'm having trouble deciding on the best approach to create a new AngularJS application. There seem to be various methods available, such as using angular-seed from https://github.com/angular/angular-seed or yeoman - http://www.sitepoint.com/kickstar ...

The way in which notifications for updates are displayed on the Stack Overflow website

Could someone shed some light on how the real-time update messages on this platform are created? For instance, when I am composing a response to a question and a new answer is added, I receive a notification message at the top of the page. How is this fun ...

Unable to retrieve the child value using getJSON

I am currently retrieving data from an API that provides information in a specific format. Here is an example of the JSON data I receive: { "total":1, "launches":[ { "name":"Falcon 9 Full Thrust | BulgariaSat-1", "net":"June 23, 2017 1 ...

Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html: https://i.stack.imgur.com/mDtSA.png Here is ...

What is the best way to establish communication between methods in a React application?

In the SelectedTopicPage component, I currently have two methods: navigateNext and render. My goal is to pass the value of topicPageNo from the navigateNext method to the render method. What is the best way to achieve this in React? When I attempt to decla ...

Despite creating a new array, Vuetify 2 continues to display 10 in the pagination options

I am facing an issue in Vuetify 2 where I have set the pagination options of a data table to be [50,60,70], but on the page, it displays [10,50,60,70]. It seems to be combining the default 10 into the list. https://codepen.io/anon/pen/NQRRzY?&editable ...

The reason why the script and div tags are so common in HTML is because they serve different purposes. However, it's

Hey there, friend! I've searched on baidu.com, cnds, and stack overflow, but couldn't find an answer. I have two questions: "why can script and div tags be used so much in HTML?" and "why is there only one html and body tag in HTML?" For example: ...

Babel not functioning properly with static class property

I'm utilizing JSDOC along with all its supported npm plugins to generate comprehensive documentation. However, I've been facing difficulties when running jsdoc and parsing JSX files, as it consistently throws an error near the "=" sign as shown b ...

Perform an Ajax call just one time

$('#addToCart').click(function () { let csrf = $("input[name=csrfmiddlewaretoken]").val(); let trTable = $(this).parents('div')[1]; let customPrice = $($(trTable).children('div') ...

The precompilation of Handlebars using Node.js encounters issues on Cloud9

I'm currently using the handlebars template precompiler for express, specifically this one, to precompile my templates in nodejs. While everything runs smoothly locally, I've encountered some issues when trying to do the same on Cloud9 IDE (Clou ...

I am unable to eliminate the parentheses from the URL

I am in need of creating a function that can extract the content inside "()"" from a URL: Despite my efforts, the function I attempted to use did not provide the desired result. Instead of removing the "()" as intended, it encoded the URL into this format ...

Troubleshooting Java REST service integration in AngularJS for UPDATE and DELETE operations

After successfully implementing a REST service with Java and testing all HTTP methods using Postman, I decided to explore AngularJS. Upon integrating it to consume the REST service, I encountered issues specifically with the Delete and Put methods not func ...

Having trouble with moving a range selector using Cypress code?

I am currently working on a cypress code that is meant to move the range selector from one location to another. While the range selector position is being selected correctly, it fails to actually move the range selector as intended. Below is the command f ...

What is the best way to embed an HTML tag along with its attributes as a string within an element?

https://i.sstatic.net/EZSOX.png Is there a way to incorporate this specific HTML tag with its distinct colors into an element within a JSX environment? I attempted the following approach: const htmlTag = '<ifx-icon icon="calendar-16"> ...

How can I create a real-time page update using node.js?

I am completely new to node.js, but my main goal in learning this language is to achieve a specific task. I want to create a webpage where the content within a designated "div" can be swapped dynamically for users currently viewing the page. For example, ...

"Resetting count feature in AngularJS: A step-by-step guide

I have a list consisting of four items, each with its own counter. Whenever we click on an item, the count increases. I am looking to reset the counter value back to zero for all items except the one that was clicked. You can view the demonstration here. ...

"Encountering a syntax error with _.map and _.zip in JavaScript

When attempting to use underscore.js with the following code: (_.map(_.zip([v,xs]),function(rs){return {a:rs[0],x:rs[1]}})) I encountered a syntax error The syntax error observed is: Token '{' is unexpected, expecting [)] at column 34 of the ...

Why won't the function activate on the initial click within the jQuery tabs?

When creating a UI with tabs, each tab contains a separate form. I have noticed that when I click on the tabs, all form save functions are called. However, if I fill out the first tab form and then click on the second tab, refresh the page, and go back t ...

Inspecting an unspecified generic parameter for absence yields T & ({} | null)

Recently, I came across a perplexing issue while responding to this specific inquiry. It pertains to a scenario where a generic function's parameter is optional and its type involves the use of generics. Consider the following function structure: func ...

Having trouble adding a property to an object, any solutions?

I've been struggling with adding a property to a nested Object in my JavaScript code. Despite setting the property name and value, the property doesn't seem to persist. populated_post.comments[i].comment.end = true console.log(typeof(populated_po ...