What is the best way to apply custom styles in reactJs to toggle the visibility of Google Maps?

There are three radio buttons that correspond to school, restaurant, and store. Clicking on each button should display nearby locations of the selected type. Displaying Google Map and nearby places individually works fine without any issues.

class PropertyMap extends React.Component{
constructor(props) {
    super(props);
    this.state = {
        propertyType: 'default',
        selectedOption: ''
    } 

    this.handleClick = this.handleClick.bind(this);
}

handleClick(e){
    this.setState({
        propertyType: e.target.value
    });
}

componentDidMount(){
    let school  = document.getElementById('school');
    let restaurant = document.getElementById('restaurant');
    let default = document.getElementById('default');

    if(this.state.propertyType == 'restaurant'){
        school.setAttribute('style', 'height:0');
        restaurant.setAttribute('style', 'height:100%');
    }
    else if(this.state.propertyType == 'school'){
        school.setAttribute('style', 'height:100%');
        restaurant.setAttribute('style', 'height:0');
    }
    else{
        school.setAttribute('style', 'height:0%');
        restaurant.setAttribute('style', 'height:0');
        default.setAttribute('style', 'height:100%');
    }
}

render(){

    let _standard = this.props.standard;
    let datax = _standard.data;
    let address = datax.address;
    let city = datax.City;
    let postcode = datax.Code;
    let st = datax.State;
    let defaultMap = (<DefaultMap mapdetails={datax} />);
    let schoolMap = (<SchoolMap mapdetails={datax}  type={this.state.propertyType} />);
    let restaurantMap = (<RestaurantMap mapdetails={datax}  type={this.state.propertyType} />);

    return(
            <div>
                <div className="container">
                    <div className="row">
                        <div className="col-md-12">
                            <div className="location-info-container">
                                <h2>Location</h2>
                                <p>
                                    {address}.
                                </p>
                                <p>
                                    {city}, {st} {postcode}
                                </p>

                                <p><b>Nearby:</b></p>
                                <label className="radio-inline">
                                    <input type="radio" name="map" id="" onChange={this.handleClick} value="school" /> School
                                </label>
                                <label className="radio-inline">
                                    <input type="radio" name="map" id="" onChange={this.handleClick} value="restaurant" /> Restaurant
                                </label>
                                <label className="radio-inline">
                                    <input type="radio" name="map" id="" onChange={this.handleClick} value="store" /> Store
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="gmap">
                    <div id="default">
                        {defaultMap}
                    </div>
                    <div id="restaurant">
                        {restaurantMap}
                    </div>
                    <div id="school">
                        {schoolMap}
                    </div>
                </div>
            </div>
        )
}

}

I'm facing an issue where the styles defined in my componentDidMount() function are not updating after clicking on the radio buttons. I want the height of the selected option (school or restaurant) to be 100% while the other should have a height of 0% when clicked. Any suggestions on why this functionality is not working?

Answer №1

Previously mentioned in a comment, componentDidMount only runs the first time a component is mounted. To perform actions before and/or after an update, you may utilize componentWillUpdate or componentDidUpdate. Reference: https://facebook.github.io/react/docs/react-component.html

If your goal is to toggle the visibility of a component based on radio button selection in React, consider a method similar to this:

class PropertyMap extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      propertyType: 'default',
      selectedOption: ''
    } 

    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick(e){
    this.setState({
      propertyType: e.target.value
    });
  }
  
  render() {
        let map = <div>Your Default component here</div>;
        switch (this.state.propertyType) {
            case 'restaurant':
                map = <div>Your Restaurant component here</div>;
                break;
            case 'school':
                map = <div>Your School component here</div>;
                break;
        }

        return(
                <div>
                    <div className="container">
                        <div className="row">
                            <div className="col-md-12">
                                <div className="location-info-container">
                                    <label className="radio-inline">
                                        <input type="radio" name="map" id="" onChange={this.handleClick} value="school" /> School
                                    </label>
                                    <label className="radio-inline">
                                        <input type="radio" name="map" id="" onChange={this.handleClick} value="restaurant" /> Restaurant
                                    </label>
                                    <label className="radio-inline">
                                        <input type="radio" name="map" id="" onChange={this.handleClick} value="store" /> Store
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="gmap">{map}</div>
                </div>
            )
    }
}

// Render it
ReactDOM.render(
  <PropertyMap />,
  document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Alternatively, if adjusting height is necessary, consider incorporating style and class attributes for better management:

class PropertyMap extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      propertyType: 'default',
      selectedOption: ''
    } 

    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick(e){
    this.setState({
      propertyType: e.target.value
    });
  }
  
  render() {
        const { propertyType } = this.state

        return(
                <div>
                    <div className="container">
                        <div className="row">
                            <div className="col-md-12">
                                <div className="location-info-container">
                                    <label className="radio-inline">
                                        <input type="radio" name="map" id="" onChange={this.handleClick} value="school" /> School
                                    </label>
                                    <label className="radio-inline">
                                        <input type="radio" name="map" id="" onChange={this.handleClick} value="restaurant" /> Restaurant
                                    </label>
                                    <label className="radio-inline">
                                        <input type="radio" name="map" id="" onChange={this.handleClick} value="store" /> Store
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="gmap">
                        <div className={(propertyType === 'restaurant') ? 'show' : 'hide'}>Your Restaurant component here</div>
                        <div className={(propertyType === 'school') ? 'show' : 'hide'}>Your School component here</div>
                        <div className={(propertyType !== 'restaurant' && propertyType !== 'school') ? 'show' : 'hide'}>Your Default component here</div>
                    </div>
                </div>
            )
    }
}

// Render it
ReactDOM.render(
  <PropertyMap />,
  document.getElementById("root")
);
.show {
  width: 100%;
  display: block;
}
.hide {
  width: 0%;
  display: none;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Answer №2

Since I was unable to give an upvote to the previous comment, I will share the resolution in this space. Following recommendations, I transferred all of the code from the componentDidMount method to the render function and found success.

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

Tips on getting your card to stay at the top

Screenshot of webpage HTML (EJS): In the HTML file, look for the section after <%- include("navbar.ejs") -%> inside the body tag. The ".cardholder" contains "anime-card" templates (card.ejs). The first and last div within ".cardholder" are ...

There are occasions when the Phaser sprite.kill() function fails to execute

Currently, I am developing games using Phaser and have encountered an issue with the sprite.kill() method. At times, when I invoke sprite.kill(), it appears that Phaser destroys the body for collisions/overlapping, but the visual elements (image and dragg ...

Can a Next.js application support multiple instances of the App component?

We are working on our next.js (v11) application where we have a variety of page types. Currently, we utilize a custom App component to manage common elements across all pages. However, I am interested in reducing redundancy even further by creating additio ...

Struggling with accessors in React Table that are not returning the expected values

Currently, I am working with React Table version 7.6.x. I have successfully implemented column filters in my React Table setup. An issue arises when attempting to filter a column where the accessor uses a return statement to render a Link Component - the ...

Disappearance of the second level in a CSS dropdown menu

I am currently working on creating a dropdown menu using only CSS. Check out this example I'm using: http://jsfiddle.net/DEK8q/8/ My next step is to center the menu, so I added position-relative like this: #nav-container { position: rela ...

Adjust the image's placement and reduce its size as the screen size decreases, without using any media queries

Essentially, I encountered an issue where I had a table row with 2 cells - the left cell containing text and the right one containing an image. As the screen size decreased, I needed the image to move below the text. After some investigation, I delved into ...

Add a new item to an array in Angular 2 when a click event occurs

I'm trying to add a new list item (which comes from an API) when a button is pressed, but I'm not sure how to do it. Can anyone provide some guidance? Here's the code: <ul> <li *ngFor="let joke of jokes">{{joke.value}}</li> ...

Unusual Methods in Vue.js: Exploring Odd Behavior

In my application, I have a single data variable called message, as well as a method in the methods section that performs cryptographic algorithms. Below is the code snippet: export default { data: () => ({ message: "" }), methods: { clic ...

CORS headers not functioning as expected for Access-Control-Allow-Origin

Can someone help me figure out how to add Access-Control-Allow-Origin: 'http://localhost:8080' in Node.js and Express.js? I keep getting this CORS error: Access to XMLHttpRequest at http://localhost:3000 from origin 'http://localhost:8080&ap ...

Why am I getting the "Cannot locate control by name" error in my Angular 9 application?

Currently, I am developing a "Tasks" application using Angular 9 and PHP. I encountered a Error: Cannot find control with name: <control name> issue while attempting to pre-fill the update form with existing data. Here is how the form is structured: ...

Cloud function -> time stamps evaluation

I've been working on a cloud function to delete items in the "links" collection that have an end time older than the current timestamp. Although my function runs without any errors, it's not deleting the items as expected and is causing me quite ...

What could be the reason for my onChange event not functioning properly?

The issue I'm experiencing involves my onchange event not properly copying the text from the current span to the hidden field. Any ideas on why this might be happening? Check out my code at this link. ...

the response code 500 was returned by the development server

Recently, I attempted to use google-trends-api in React Native. I followed the instructions provided in the description and loaded the module like this: const googleTrends = require('google-trends-api'); after installing google-trends-api via ...

What is the function of this.handleClick that is positioned on the LEFT side of the = operator?

I'm struggling to understand the usage of this in an ES6 constructor. Initially, I grasped the following concepts (see example below): - We utilize this.height = height; to introduce a new instance variable. - Adding a new instance method with cl ...

Retry request with an AngularJS interceptor

Currently, I am in the process of developing an Angular application and encountering some challenges while implementing a retry mechanism for the latest request within an HTTP interceptor. The interceptor is primarily used for authentication validation on ...

Unable to retrieve Google Maps route on Android device

After discovering the route between two latitude and longitude values on Google Maps using "Get Directions," everything appears accurately. However, when attempting to use the same directions in an Android mobile application, only the destination marker ...

ASP.NET MVC does not automatically refresh when changes are made to the CSS file

Currently, I am diving into the world of Bootstrap 4 within an ASP.NET MVC project, exclusively making changes to the index.cshtml file in JetBrains Rider. However, I've encountered a strange issue that has me stumped. Each day, when I begin writing ...

strange occurrences in localToWorld transformation

Hello there! Currently, I'm working on a project where I'm generating a TextMesh using font geometry and placing it within an empty pivot object. My goal is to obtain the world coordinates of each vertex in the TextMesh so that I can manipulate ...

Display the HTML content retrieved from the SailsJS Controller

Exploring the world of SailsJS, I am on a mission to save HTML content in a database, retrieve it, and display it as rendered HTML. To achieve this goal, I have set up a sails model and a controller. This is what my model looks like: attributes: { ht ...

Show a pop-up form when a user focuses on it using React

Hello, I have been looking for a way to create an overlay with a form that appears when a specific input field is clicked. I am trying to achieve this using React. Can someone please advise me on how to accomplish this? Here is my code import React, { Co ...