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

Designing a multi-platform web browser application for Android, iOS, and Windows 10

I've developed several web applications using HTML5 technology and now I'm interested in creating my own custom web browser specifically tailored for my apps/sites. I want it to have a native appearance, but essentially just wrap around my web ap ...

What is the method for retrieving the currently selected value in a MultiColumnComboBox within Kendo for Angular?

Check out this live example created by the official Telerik team: I need to extract the id (referenced in contacts.ts) of the currently selected employee when clicking on them. How can I access this information to use in another function? ...

Executing Lambda functions on DynamoDB has no effect

Below is the code snippet for a Lambda function: console.log('Loading function'); var aws = require('aws-sdk'); var ddb = new aws.DynamoDB(); function retrieveUser(userid) { var query = ddb.getItem({ TableName: "Users", ...

Utilizing TypeScript to Define Object Properties with String Keys and Values within Parentheses

I am in the process of developing a telegram bot I have the need to save all my messages as constants My message schema is structured as follows: type MessagesSchema = { [K in keyof typeof MessagesEnum]: string } Here is an example implementatio ...

Exploring the world of Restify: Mastering the art of sending POST

Having trouble reading the body of a request while trying to create an API with Restify. Snippet from main.js: 'use strict'; const perfy = require('perfy'); perfy.start('startup'); const restify = require('rest ...

Tips for loading a webpage based on the selected value of a JQuery dropdown list

I'm currently working on an ASPX webpage where I am developing a feature to create reports using filter criteria. To populate my dropdown list, I am using a jqxwidget which retrieves values from a variable I have defined: var sourceRptType = [ ...

What prevents me from displaying the image in the Bootstrap tooltip?

I am currently utilizing the Bootstrap framework v3.3.0 for my website. I'm trying to implement an image as a tool-tip when the user hovers their mouse pointer over an icon. Here is the HTML code I have: <div class="col-sm-5"> <div class= ...

Is it possible to implement a route within a controller in Express.js?

In my controller, I currently have the following code: module.exports.validateToken = (req, res, next) => { const token = req.cookies.jwt; //console.log(token); if (!token) { return res.sendStatus(403); } try { const ...

larger breakpoints are always overridden by smaller breakpoints

Is there a way to prevent smaller breakpoints from overriding the styles of larger breakpoints? I've attempted the following: <Box mt={{ lg: 0, md: 2 }}></Box> Unfortunately, the styles specified for lg: 0 were overridden by the ones gen ...

Displaying the API request using the UseEffect API is not working upon the page

Sorry if this question has been asked before, but I’m really stuck on this small bug. I’m trying to display a collection of tweets from Firestore when the page loads, but currently it only works after a post request. Here’s my code: useEffect(() ...

display dynamic graphs using json data from a php backend

I'm having trouble displaying a graph using JSON data in Highcharts. Here is a sample of what I need: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-rotated-labels/ The file values ...

What is the solution for the error "BREAKING CHANGE: webpack < 5 used to automatically include polyfills for node.js core modules"?

I am trying to use the "web3" and "walletconnect/web3-provider" package in a Vue & Laravel 8 project. I have installed it using the npm i --save web3 @walletconnect/web3-provider command and then added the following code to import into ...

The updateItem function in the JSGrid controller was not called

Currently, I am working on a project involving js-grid. However, I have encountered an issue where the updateitem function of the controller is not being invoked when attempting to update a column field. Additionally, the field resets to its old value wi ...

Tips for sending a form with the <button type="submit"> element

I created a login form and initially used <button type="submit">, but unfortunately, it was not functioning as expected. However, when I switched to using <input type="submit">, the form submission worked perfectly. Is there a JavaScript method ...

Positioning a div on the right side of its parent div

Hi there! I'm currently working on a small navbar that has two sections: the left section with an arrow icon and the right section with two icons - an envelope and an exclamation triangle. I've been trying to position the right section in the top ...

JavaScript Indexed Array Names: Managing Arrays with Indices

I have a collection of arrays named "list0" through "list7" which have been explicitly defined. My goal is to include each of these arrays as elements in an existing array, creating a 2D array of these defined arrays. How can I reference each 'list&a ...

The update feature seems to be malfunctioning within the MEAN Stack environment, specifically with node.js and angular js

Looking for some assistance as a beginner in the mean stack. I'm trying to update a record using the update function, but it's not working as expected. I need to update a specific object based on its ID, however, I'm encountering issues wit ...

Creating a post request in Express.JS with an empty object

Currently, I am working with Express version 4.18.2. I have created routing and controller files along with an HTML form that uses the POST method. However, when I submit the form, I attempt to display the req.body object sent in the request through the co ...

Verifying Initialization Before Destructing jQuery File Upload

I'm currently working with the blueimps jQuery file upload plugin and I need to delete all existing instances before creating new ones. The issue I'm running into is that I receive an error when attempting something like this: $('.upload&ap ...

Experimenting with React component functionality using Enzyme and Jest

Currently, I am in the process of testing a component that follows the Container/Presentational pattern. To achieve 100% coverage, I need to test the handleChange() function which contains a setState() method. The challenge lies in the fact that I am only ...