What's the best way to modify the style property of a button when it's clicked in

I am working with a react element that I need to hide when a button is clicked.

The styles for the element are set in the constructor like this:

  constructor(props) {
    super(props);
    this.state = {
      display: 'block'
    };
    this.ElementStyle= {
      width: '100%',
      backgroundColor: '#F6F6F6',
      color: '#404040',
      padding: '8px 15px',
      boxSizing: 'content-box',
      position: 'fixed',
      bottom: '0',
      display: this.state.display
    }
  }

The element contains a button inside its render() method which calls a function to change the state:

  render()  {
    <button onClick={this.Method.bind(this)}>Click me </button>
  }

Here is the Method():

  Method() {
    this.setState({
      display: 'none'
    });
  }

Additionally, in the shouldComponentUpdate() method:

  shouldComponentUpdate() {
    this.ElementStyle.display = this.state.display;
  }

However, running this code results in a

"TypeError: "display" is read-only"
error.

Answer №1

Just put your styles in the state:

State

this.state = {
  ElementStyle: {
    width: '100%',
    backgroundColor: '#F6F6F6',
    color: '#404040',
    padding: '8px 15px',
    boxSizing: 'content-box',
    position: 'fixed',
    bottom: '0',
    display: 'block'
  };
}

Method

 Method() {
    this.setState({
      ElementStyle: {
        ...this.state.ElementStyle,
        display: 'none'
      }
    });
  }

Render

render()  {
  <button style={this.state.ElementStyle} onClick={this.Method.bind(this)}>Click me </button>
}

Answer №2

To enhance your component's style, consider setting the initial display to none using the following CSS:

// css
.yourclass {
 width: '100%',
  backgroundColor: '#F6F6F6',
  color: '#404040',
  padding: '8px 15px',
  boxSizing: 'content-box',
  position: 'fixed',
  bottom: '0',
  display: none
    }
}

// Create a class that toggles display to block
.show {
  display: block;
}

In your JavaScript code, you can manage the state and update the display property accordingly:

// Set the initial state for the hidden element
this.state = {
   showHiddenElement: false
}

// Toggle the state to change the display property
const {showHiddenElement} = this.state;
this.setState({
  showHiddenElement: !showHiddenElement
})

// Apply the appropriate class based on the state in your component
const toggle = this.state.showHiddenElement;
<yourelement className={`yourclass ${toggle? 'show' : ''}`}

This approach offers flexibility in managing the visibility of elements within your component. Let me know if you have any questions or need further clarification!

Answer №3

incorrect action taken react utilizes a virtual dom, which is automatically managed, however you are attempting to modify its behavior, perhaps you could handle it in this manner:

constructor(props) {
    super(props);
    this.state = {
       display: 'block'
    };
}


Method() {
   this.setState({
       display: 'none'
   });
}


render()  {
  <div>
     <div style={{display: this.state.display}} ></div>
     <button onClick={this.Method.bind(this)}>Click me </button>
  </div>
}

there are also other options available, but this is the simplest approach.

Answer №4

Using the style property to set styles directly on elements is not the recommended approach. It's better to use CSS classes and stylesheets for styling, and then modify classes during runtime.

In your case, you can define the styles in a class, let's say in App.scss:

.class-to-be-applied {
    width: 100%;
    background-color: #F6F6F6;
    color: #404040;
    padding: 8px 15px;
    box-sizing: content-box;
    position: fixed;
    bottom: 0;

    .no-display {
        display: none;
    }
}

Then, in App.js,

import React, { Component }  from 'react';
import classnames from 'classnames';
import './App.scss';

class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            display: true
        };
    }
    handleButtonClick = () => {
        this.setState(({ display }) => ({display: !display}));
    }
    render()  {
        return (
            <div>
                <button onClick={this.handleButtonClick}>Click me </button>
                <SomeComponent className={classnames('class-to-be-applied', {'no-display': !this.state.display})} />
            </div>
        );
    }
}

Another way to achieve the same result, and a more preferred method, is to conditionally render the component so it's not inserted into the DOM tree at all. Here's how you can do it in App.js,

import React, { Component }  from 'react';
import classnames from 'classnames';
import './App.scss';

class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            display: true
        };
    }
    handleButtonClick = () => {
        this.setState(({ display }) => ({display: !display}));
    }

    render()  {
        return (
            <div>
                <button onClick={this.handleButtonClick}>Click me </button>
                { this.state.display && <SomeComponent className='class-to-be-applied' /> }
            </div>
        );
    }
}

Answer №5

1) Embed your element within inline CSS code :-

render() {
    return (
        <div>
            <button onClick={ this.Method.bind(this) }>Click me </button>
            <h1 style={{
                 width: '100%',
                 backgroundColor: '#F6F6F6',
                 color: '#404040',
                 padding: '8px 15px',
                 boxSizing: 'content-box',
                 position: 'fixed',
                 bottom: '0',
                 display:this.state.display
            }}>About</h1>
        </div>
    )
}

2) Delete the shouldComponentUpdate() method

 shouldComponentUpdate() {
this.ElementStyle.display = this.state.display;
}

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

Error: Module 'electron-prebuilt' not found

I am encountering an issue with my Electron app that utilizes Nightmare.js after compiling it into an .exe file using electron-packager. Everything functions properly until I click a button that triggers Nightmare.js, at which point I receive the followi ...

Is there a more efficient method than creating a separate variable for the navbar on each individual page where it is being utilized?

Apologies for the unclear title, I struggled to find the right wording and decided it would be easier to illustrate with code. Let's assume I have the following routes: router.get('/chest', (req, res)=>res.render('muscles/chest/chest ...

Can someone provide guidance on utilizing the index correctly within this v-for to prevent any potential errors?

I am encountering an issue with using index in a v-for loop to implement a function that deletes items from an array. The linter is flagging "index is defined but never used" as an error. I am following the instructions provided in a tutorial, but I am un ...

What is causing the UI to change every time I add a tag to refresh the web view?

Recently, I added a pull-to-refresh feature to my React Native webview app using the react-native-pull-to-refresh library. After implementing the tag, I noticed that the UI got rearranged with the webview shifted down and the top half occupied by the pull- ...

Submit a form using Ajax without having to reload the page

Seeking help for implementing an ajax form submission with four answer options to a question. The goal is to submit the form without reloading the page upon selecting an option. Below is the code I have been working on. Any suggestions or solutions are wel ...

Encountering difficulties in creating an app with Apache Cordova

After setting up the proxy settings, I attempted to create a new app named "hello" using Cordova with the following commands: npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080 The creation comman ...

Is it true that Javascript's onclick global event handlers fire prior to the page being fully loaded

I'm trying to set a global event handler for an image, but running into issues. When I use the code document.getElementById("post_image").onclick = photoEnlarge;, it returns an error saying Uncaught TypeError: Cannot set property 'onclick' ...

Learn the process of creating a unique item layout to suit your preferences

Exploring the use of div to create the desired layout but struggling to achieve my goal .skills-container { height:50px; /* aiming for around 50px */ padding:5px; } .skill-pic { width:48px; height:48px; } .skill-content { } .skill-content p { } .progres ...

Navigating following a JQuery AJAX request in PHP

After clicking the login button, I utilize JQuery's POST method to retrieve data from login.php to check if the login was successful. If it fails (no user found), the appropriate message is displayed. However, when attempting to redirect a user (whic ...

How to Send an Array to AJAX and Retrieve the Data in Codeigniter Controller

I am attempting to retrieve table data, store it in an array, and pass it to the controller so I can write it in PHP Excel. Previously, I had success with other data but now my excel file is turning up empty. Below is the JavaScript code snippet: var Ta ...

Methods for bypassing a constructor in programming

I am working on a code where I need to define a class called programmer that inherits from the employee class. The employee class constructor should have 4 parameters, and the programmer class constructor needs to have 5 parameters - 4 from the employee c ...

Steps for inserting buttons into rows of a material-ui data grid

I'm facing an issue while trying to add buttons in each row of the material-ui data grid. Instead of displaying the button, it shows [object Object]. You can see the output in the image linked below. Below is the code snippet I am using: import { D ...

Troubleshooting: 404 Error When Trying to Send Email with AJAX in Wordpress

In the process of creating a unique theme, I encountered an interesting challenge on my contact page. I wanted to implement an AJAX function that would allow me to send emails directly from the page itself. After conducting some research, I managed to find ...

How can the <animate /> tag be triggered using only CSS and HTML?

Looking for a way to trigger the animation rules of the <animate /> tag using only HTML and CSS. Is there a new standard in HTML and CSS that allows something like input:checked ~ svg animate {enabled:true;} coming up in 2020? Or some other creative ...

`The submit button fails to function properly within the Capacitor application`

Encountering a bug where clicking the Login button does not trigger any action. It works fine in the browser but encounters issues with capacitorJS. Attempts have been made to resolve this by adding an onClick function directly on the button, removing Form ...

Is there a way to gather information from a web service and neatly display it within an HTML table?

Is it possible to fetch a JSON array from a web service and save it in a variable? Consider the following table structure: <table id="myTable" border="1"></table> The table is populated using the code below: // JSON array var myData = metho ...

What could be causing images in the public folder to fail loading in Nextjs?

Starting from the root of my project, there is an image called download.png located in the public folder. I'm trying to display this image in my JavaScript file with the following code: <img src={"/download.png"} />. However, the image ...

How can I convert the left links in my navigation bar to a CSS drop-down menu to make it more responsive on small screens?

Here is the structure of my HTML (at the top): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></s ...

Discover the child of the delegated event div using jQuery

Can you assist me in resolving this issue? My HTML structure appears as follows: <div id="main-randompart"> <!--Inserted into the DOM during runtime--> <div class="close"> X </div> <img src="somesrc..."> ...

Whenever a button is clicked in a custom column rendering of a React material table, the sorted state is lost. This issue occurs whenever any state update is triggered

I encountered an issue with my code involving a Collapsible list triggered by an Icon Button. After sorting the table and then expanding the list, the table reverts back to its original unsorted state. I am puzzled as to why this is happening. <Material ...