Ad

How To Change Value Of Display Property After It Has Been Set To Display: None

- 1 answer

First of all sorry if the question title is confusing, I couldn't figure out how else to put it.
I am working on a React application. I am supposed to make a custom Alert component for my application which I did. I also put a button to dismiss the alert. Following is my alert component.

Alert Component

import React from 'react';
import './styles.css';
const Alert = ({ text, type }) => {
    function closeAlert(event) {
        event.target.parentElement.style.display = 'none';
    }

    return ( 
        <div className = "alert" id = { type }>
        <span className = "closebtn" onClick = { closeAlert }>& times;</span> 
            { text } </div>
    );
};
export default Alert;

So my issue is something like this:
When I click the Login button and the user has entered invalid credentials, I display an error alert. I dismiss the alert by clicking the &times sign. Then I click Login a second time, again with wrong credentials. But this time the alert doesn't show up because I did display: none on the previous click. Please suggest a solution.

Ad

Answer

You could save the status of the Alert in the parent component like in the following example.

You can then show or not the Alert component with { showAlert && <Alert/> }

const Alert = ({ text, type, closeAlert }) => {
    return ( 
        <div className = "alert" id = { type }>
          <span className = "closebtn" onClick = { closeAlert }>& times;</span> 
          { text } 
        </div>
    );
};

class Hello extends React.Component {
  state = {
    showAlert: false
  };
  
  closeAlert = () => this.setState({ showAlert: false });
  showAlert = () => this.setState({ showAlert: true });
  
  render() {
    const { showAlert } = this.state;
    return 
      (<div>
        <button onClick={this.showAlert}>Show</button>
        { showAlert && <Alert text="ERROR" type="error" closeAlert={this.closeAlert}/> }
      </div>);
  }
}

ReactDOM.render(
  <Hello/>,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="container">
</div>

Ad
source: stackoverflow.com
Ad