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

@ -1,46 +1,49 @@
---
title: Collapse
tags: components,children,state,intermediate
tags: components,children,state,beginner
---
Renders a component with collapsible content.
- Use the `React.useState()` hook to create the `isCollapsed` state variable with an initial value of `collapsed`.
- Use an object, `style`, to hold the styles for individual components and their states.
- Use a `<div>` to wrap both the `<button>` that alters the component's `isCollapsed` state and the content of the component, passed down via `children`.
- Determine the appearance of the content, based on `isCollapsed` and apply the appropriate CSS rules from the `style` object.
- Finally, update the value of the `aria-expanded` attribute based on `isCollapsed` to make the component accessible.
- Use the `useState()` hook to create the `isCollapsed` state variable with an initial value of `collapsed`.
- Use the `<button>` to change the component's `isCollapsed` state and the content of the component, passed down via `children`.
- Determine the appearance of the content, based on `isCollapsed` and apply the appropriate `className`.
- Update the value of the `aria-expanded` attribute based on `isCollapsed` to make the component accessible.
```css
.collapse-button {
display: block;
width: 100%;
}
.collapse-content.collapsed {
display: none;
}
.collapsed-content.expanded {
display: block;
}
```
```jsx
const Collapse = ({ collapsed, children }) => {
const [isCollapsed, setIsCollapsed] = React.useState(collapsed);
const style = {
collapsed: {
display: 'none'
},
expanded: {
display: 'block'
},
buttonStyle: {
display: 'block',
width: '100%'
}
};
return (
<div>
<button style={style.buttonStyle} onClick={() => setIsCollapsed(!isCollapsed)}>
<>
<button
className="collapse-button"
onClick={() => setIsCollapsed(!isCollapsed)}
>
{isCollapsed ? 'Show' : 'Hide'} content
</button>
<div
className="collapse-content"
style={isCollapsed ? style.collapsed : style.expanded}
className={`collapse-content ${isCollapsed ? 'collapsed' : 'expanded'}`}
aria-expanded={isCollapsed}
>
{children}
</div>
</div>
</>
);
};
```