How To Change Value Of Display Property After It Has Been Set To Display: None
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 ×
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.
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>
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM