Update snippets

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-11-03 20:42:15 +02:00
parent 9142a60275
commit 36179e57dc
4 changed files with 84 additions and 72 deletions

View File

@ -3,14 +3,12 @@ title: Alert
tags: components,state,effect,beginner
---
Creates an alert component with `type` prop.
Renders an alert component with `type` prop.
- Define appropriate CSS styles and animations for the component's elements.
- Use the `React.useState()` hook to create the `isShown` and `isLeaving` state variables and set their values to `false`.
- Use the `useState()` hook to create the `isShown` and `isLeaving` state variables and set both to `false` intially.
- Define `timeoutId` to keep the timer instance for clearing on component unmount.
- Use the `React.useEffect()` hook to update the value of `isShown` to `true` and clear interval by using `timeoutId` when component is unmounted.
- Define `closeAlert` function to set the component is removed from DOM by displaying fading out animation and set `isShown` to `false` via `setTimeout()`.
- Define the component, which renders the alert component with user defined `message` and a close button to remove the component from DOM.
- Use the `useEffect()` hook to update the value of `isShown` to `true` and clear the interval by using `timeoutId` when the component is unmounted.
- Define a `closeAlert` function to set the component as removed from the DOM by displaying a fading out animation and set `isShown` to `false` via `setTimeout()`.
```css
@keyframes leave {
@ -28,19 +26,19 @@ Creates an alert component with `type` prop.
position: relative;
}
.alert.warning{
.alert.warning {
color: #856404;
background-color: #fff3cd;
border-color: #ffeeba;
}
.alert.error{
.alert.error {
color: #721c24;
background-color: #f8d7da;
border-color: #f5c6cb;
}
.alert.leaving{
.alert.leaving {
animation: leave 0.5s forwards;
}
@ -58,7 +56,7 @@ Creates an alert component with `type` prop.
font-size: 16px;
}
.alert .close:after{
.alert .close:after {
content: 'x';
}
```
@ -85,15 +83,23 @@ const Alert = ({ isDefaultShown = false, timeout = 250, type, message }) => {
}, timeout);
};
return isShown && (
<div className={`alert ${type} ${isLeaving ? 'leaving' : ''}`} role="alert">
<button className="close" onClick={closeAlert} />
{message}
</div>
return (
isShown && (
<div
className={`alert ${type} ${isLeaving ? 'leaving' : ''}`}
role="alert"
>
<button className="close" onClick={closeAlert} />
{message}
</div>
)
);
};
```
```jsx
ReactDOM.render(<Alert type="info" message="This is info" />, document.getElementById('root'));
ReactDOM.render(
<Alert type="info" message="This is info" />,
document.getElementById('root')
);
```