Show/Hide button on React Native Toolbar

I am having trouble with implementing a hide/show button in the header of a React Native Toolbar. My goal is to display the buttons only after the user has logged in. However, I keep getting an error that says undefined is not an object for this.state.status. How can I access the state within the toolbar?

export default class TestSC extends React.Component {
  constructor(){
    super();

    this.state ={
      status:false
    }
  }


  static navigationOptions = ({navigation})=> {
    return {
    title: 'Tin Tin Foil',
     headerRight: ( 
      <View style={styles.twoButtonView}>
         {(this.state.status == true) ?  
          <TouchableOpacity onPress={this._refreshButtonPress}>
            <Image source={require('../img/ic_search_white.png')} style={styles.refrgeshButton}  />
          </TouchableOpacity>
        : null} 
        <Button
          onPress={() => navigation.navigate('Login')}
          title="Login" color="#fff" />
      </View>
    ),
  }};

  toggleStatus(){
    this.setState({
      status:!this.state.status
    });
    console.log('toggleStatus: '+ this.state.status);
  }

  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Test</Text>

          <TouchableHighlight onPress={()=>this.toggleStatus()}>
            <Text> Click Me Toggle </Text>
          </TouchableHighlight>
      </View>
    );
  }
  }

Answer №1

To achieve this, utilize the navigation parameters.

When updating the component state, ensure to update the Navigator parameters as well.

this.props.navigation.setParams({
    status: true
})

Then, incorporate the navigator parameters in the header.

navigation.state.params.status == true

Here is a complete example:

export default class TestSC extends React.Component {
  constructor() {
    super();

    this.state = {
      status: false
    }
  }

  static navigationOptions = ({navigation, screenProps}) => {  
    if (!navigation.state.params) {
      navigation.state.params = {}
    }
    return {
      title: 'Tin Tin Foil',
      headerRight: ( 
        <View style={styles.twoButtonView}>
          {(navigation.state.params.status == true) ?  
            <TouchableOpacity onPress={this._refreshButtonPress}>
              <Text>Login</Text>
            </TouchableOpacity>
          : null}
        </View>
      ),
    }
  };

  toggleStatus() {
    this.setState(pre => {
      pre.status = !pre.status
      this.props.navigation.setParams({
        status: pre.status
      })
      return pre
    })

    console.log('toggleStatus: ' + this.state.status);
  }

  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Test</Text>

          <TouchableHighlight onPress={()=>this.toggleStatus()}>
            <Text> Click Me Toggle </Text>
          </TouchableHighlight>
      </View>
    );
  }
}

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

Ways to eliminate / refresh locomotive scroll when resizing the window?

I am currently working on a website that is designed with a horizontal layout for desktop screens, but switches to a vertical layout for smaller screens. I have implemented locomotive scroll successfully, but I am facing issues with window resizing. Below ...

I lose my user interface after a series of clicking events

I've created a React application that generates new quotes without repetition, but I'm encountering an issue where the UI disappears after clicking enough times. What could be causing this behavior in my code? The console displays an object error ...

Import files from local directory to iframe in Electron application

I am currently working on an application using Electron that allows users to preview HTML5 banner ads stored locally on their computer. At this point, I have enabled the ability to choose a folder containing all the necessary files. Once a directory is s ...

The method .depth() does not exist within this context

When I attempted to execute this code using npm start in the terminal //index.js const api = require('./api'); console.log('Starting monitoring!'); setInterval(async () => { //console.log(await api.time()); console.log(await ...

Prevent the hover() effect from affecting all div elements at once

I am aiming to achieve a function where hovering over a div with the "rectangle" class will display another div with the "description" class. Initially, the description div will have a display value of "none", but upon hovering, it should become visible. ...

Is it possible to update mobile apps from a remote server after they have been published?

I am a newcomer to the world of mobile development and currently, I am working on a web app that sells stock images using PHP/MySQL. I am now looking to create an Android/iOS version of the website with essential core functionalities, focusing on accessing ...

The concept of variables within the jQuery each function

Can someone provide assistance? I want the variables id, zIndex, and width inside the function to be defined after jQuery.each is called, with their values coming from the array passed to the function MyFunction: console.log(id); //ID IS NOT DEFINED con ...

To avoid any sudden movements on the page when adding elements to the DOM using jQuery, is there a way to prevent the page from

I have a challenge where I am moving a DIV from a hidden iFrame to the top of a page using jQuery. Here is my current code: $(document).ready(function($) { $('#precontainer').clone().insertBefore(parent.document.querySelectorAll(".maincontainer" ...

The menu starts off in the open position when the page loads, but it should remain closed until it

I'm having trouble with my menu; it displays when the page loads but I want it to be closed and then open when clicked. Despite my best efforts, I can't seem to fix this issue. <html> <head> <script> $(document).ready(funct ...

Troubleshooting Problem with MVC Ajax Requests

When working with an MVC view, I have a submit button that includes validation checks. If the validation fails, I return false to prevent the form from being submitted. In addition to standard validation, I also use an Ajax GET request to check for duplic ...

Node.js and EJS are throwing an error, indicating that the file.ejs is unable to identify the variable definitions

I am facing an issue with my express.js server template. A 'x is not defined' error keeps popping up, but I can't seem to find where the problem lies. I even checked a friend's code from the same tutorial, and it works on his machine. ...

Guide on how to retrieve a list of objects from a controller and showcase them utilizing JQuery in a Spring MVC application with ajax functionality

Here is the controller code snippet: @Controller public class MainController { @Autowired SqlSession sqlSession; @Autowired Message messageVO; @RequestMapping(value="getMessages", method=RequestMethod.GET) public @ResponseBody List<Messag ...

Using ag-Grid to bind data from an external service file

Just getting started with angular and exploring ag-grid. I have a service in one file and a controller in another, where I am able to see the grid column headers but struggling to bind the data from my service to the grid. Can someone please point out what ...

Could you please provide the NodeJS ES6 alternative syntax for importing the PouchDB library using the `let` keyword?

Currently, I am following a tutorial at https://medium.com/beginners-guide-to-mobile-web-development/getting-started-with-pouchdb-f0f3d7baebab on incorporating PouchDB into a server-side NodeJS script. However, I have encountered an issue in Step 1: cons ...

Ways to display two horizontal scrolling menu bars

I am in need of displaying two horizontal scroll menu bars on my website. After some research, I came across a custom horizontal scroll menu with left and right arrows. https://jsfiddle.net/c5grnve6/ While it works well with only one scroll menu on the p ...

A step-by-step guide to displaying image upload previews using React

I am currently working on developing an image upload form with the use of Next.js/React.js. The goal is to allow users to assign tags to each uploaded image and display a preview of the image using 'URL.createObjectURL'. Although the uploading pr ...

Executing JS Command on a Different Webpage using nodejs

Picture a scenario in which I visit a specific website and access the console within Chrome. Then, I type console.log(a_Variable_name); and receive a result. How can I retrieve this exact value within my JS Code/React? ...

Determine the total value of various dynamic elements by utilizing jQuery/Javascript for calculation

I am currently working on a project that involves a dynamic list of products in a cart. I need to calculate the total price of all the products in the cart, but I am having trouble figuring out how to access and calculate the values from these dynamic elem ...

Transform a JSON array containing individual objects into a new JSON array with objects

My array contains objects with nested objects in each element, structured like this: [ { "person": { "name": "John", "isActive": true, "id": 1 } }, { "person": { "name": "Ted", "isActive": true, "id": 2 } } ] I ...

Bootstrap modals are refusing to open

I have encountered an issue where the images are not displaying on my modal. I have tried changing both the images and the code itself, but being new to this, I am unsure of what exactly is causing the problem. Could it be a fault in the Javascript code or ...