Update Button Visibility Based on State Change in ReactJS

Currently, I'm utilizing a Material UI button within my React application. Despite changing the state, the button remains visible on the screen. Here's the relevant code snippet:

function MainPage() {
    const state = useSelector(state => state.loginDetails.state)

    const [visibilitySetting, setVisibility] = useState(true)

    useEffect(() => {
      console.log(state.loginType)
      if(state.loginType=="google")
      {
          setVisibility(false)
      }
    }, [])   
    

    return (
      <div style={{ height: 400, width: '100%' }}>
        <Button color="primary" variant="contained" style={{display:visibilitySetting}}   >
          Group
        </Button>
)

After verifying that state.loginType is indeed google,

I attempted setting display to none but observed no visible change in the button.

Answer №1

To ensure that useEffect runs every time the state changes, make sure to include the relevant state variable in the dependency array.

Here's an example:

 useEffect(() => {
      console.log(state.loginType)
      if(state.loginType==="google")
      {
          setVisibility(false)
      }
    }, [state.loginType])

For conditional rendering of the button component:

{visibilitySetting && <Button color="primary" variant="contained">
          Group
        </Button>}

Implementing this adjustment should effectively address the issue at hand.

Answer №2

When setting the true and false values for the display property, it is important to also check the condition.

<Button ... style={{display: visibilitySetting ? 'block' : 'none'}}>

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

Implementing a custom focus effect for MuiLink

I am looking to customize the appearance of the focusVisible property for all the (material ui) Links in my application. I am aware that I can achieve this by: const useStyles = makeStyles(() => ({ focus: { backgroundColor: 'yellow', ...

creating a loop to handle AJAX requests for JSON data

My JSON call successfully loads the data.root.offer[0].region data into a div with the class .region. Here is the code snippet: $.getJSON('json/data.json', function(data) { $('.region').html('<p>' + data.root.offer[0] ...

Experiencing a WEB3js error in a Vite, React, TypeScript application: Troubleshooting TypeError with callbackify function absence

Hey there, I've been experimenting with using web3 in a React client application (specifically with vite react-ts). When trying to call web3.eth.net.getId(), I encountered an error mentioning that callbackify is not a function. After some investigatio ...

Exploration of the "display: none;" property and loading of content

I am struggling to find concrete information on how "display: none;" affects content loading. I have always believed that certain browsers do not load external resources within content that is styled with "display: none". Is this still inconsistent across ...

Eliminate duplicate objects from arrays of objects by a specific key name

Here are some arrays of objects I am working with: var arr = [ {name: 'john', last: 'smith'}, {name: 'jane', last: 'doe'}, {name: 'johnny', last: 'appleseed'}, {name: 'johnson', ...

The alignment of the pagination in Mui datatables is currently not functioning

Currently, I am utilizing mui-datatables v ^4.2.2 with react and react-dom 17.0.2 alongside @mui/material v5.10.15. Upon displaying the datatable, I have noticed that my pagination alignment appears to be distorted: https://i.stack.imgur.com/Fhed7.png T ...

Ensure the footer remains fixed while scrolling

For the past day, I've been tackling a challenge with my online shop project. On the specific item's page, I want to include a fixed [add to cart] button as a footer initially, which then becomes sticky when scrolling to a certain point. You can ...

It is impossible for me to invoke a method within a function

I am new to working with typescript and I have encountered an issue while trying to call the drawMarker() method from locateMe(). The problem seems to be arising because I am calling drawMarker from inside the .on('locationfound', function(e: any ...

What is the best way to ensure that the bootstrap nav tab content fits perfectly on one line?

Check out this bootstrap navbar example You can see a screenshot here. <ul class="nav nav-tabs" style="display: inlne-block"> <li class="nav-item" style="text-align: center; display: inline;"> <div> <a class="nav ...

Position a dynamic <div> in the center of the screen

My goal is to design a gallery page with a list of thumbnails, where clicking on a thumbnail will open the related image in a popup div showing its full size. The issue I'm facing is how to center the popup div on the screen, especially when each pic ...

issue with making simultaneous async requests in PERN stack application

In the process of developing an inventory management application using PERN stack, I encountered a challenge with a modal where I need to make 2 GET requests. While both requests return a Status 200 response when logged in the front end, the issue arises w ...

Gulp- Ensuring the latest versions of your javascript files

I have implemented bundling and minification for my JavaScript files using gulp. What I am aiming to achieve is that whenever I make a change in any of my files and run gulp, a new bundled and minified file with a version number is generated. For example: ...

Encountering the "Cannot set headers after they are sent to the client" error within an Express.js application

In my recent project, I created a middleware to authenticate users and verify if they are verified or not. Initially, when I access protected routes for the first time, everything works fine and I receive success messages along with verification of the JWT ...

Unable to get React key={row._id} to function properly

I am having trouble accessing the mongodb default _id property in a react jsx block. Despite confirming that the _id key exists on the row object passed to the functional component ProductTableSingleRow, I still cannot read it. const ProductTableSingleRow ...

Obtaining the correct information from an array using Ionic's Angular framework

I am currently working with an array of data that contains arrays within each item. I have been able to display the data as needed, except for the IDs. Approach Show arrays within the array Retrieve the IDs of the arrays (excluding the IDs inside the ar ...

Implementing setInterval() leads to the dynamic alteration of images

I've created Marquees using CSS animations and a countdown timer. The Marquees display 100 random images that move from left to right and right to left. However, when the countdown timer decreases, the images in the Marquee change but the scrolling co ...

website pages loading faster than images can load

I run a website dedicated to music instruments, and I have implemented a carousel feature that displays images at intervals. However, I encountered an issue when converting my high-resolution images to base64 for storage in the database ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...

What is the best way to delete a property from an object in an array using Mongoose? This is crucial!

Doc - const array = [ { user: new ObjectId("627913922ae9a8cb7a368326"), name: 'Name1', balance: 0, _id: new ObjectId("627913a92ae9a8cb7a36832e") }, { user: new ObjectId("6278b20657cadb3b9a62a50e"), name: 'Name ...

Having trouble transmitting JSON data to an Express server through the browser

I have set up two servers: the first one is for frontend (localhost:7200), and the second one is for backend (localhost:7300). There is a test request made by the frontend to the backend on the route '/test'. The issue arises when I attempt to s ...