Created
July 2, 2019 09:29
-
-
Save jaksm/61bbf2e1161b3f375639db94f59c3170 to your computer and use it in GitHub Desktop.
Nice example on usage of hooks.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import PropTypes from "prop-types"; | |
import React, { useEffect, useState } from "react"; | |
import styled from "styled-components"; | |
import { color } from "../../theme"; | |
const Container = styled.div` | |
margin: 12px 0; | |
`; | |
const ListCardContainer = styled.div` | |
margin: 0 !important; | |
padding: 12px; | |
`; | |
const ListCardExpandedContainer = styled.div` | |
background: ${color.grey}; | |
padding: 12px; | |
`; | |
const isMobile = () => window.innerWidth <= 700; | |
const ListCard = props => { | |
const { mobileOnly, children, render } = props; | |
const [expanded, setExpanded] = useState(false); | |
const [shouldDisplay, setShouldDisplay] = useState(!mobileOnly || isMobile()); | |
const handleResize = () => setShouldDisplay(!mobileOnly || isMobile()); | |
useEffect(() => window.addEventListener("resize", handleResize)); | |
if (shouldDisplay) { | |
return ( | |
<Container> | |
<ListCardContainer | |
className={"list-component"} | |
onClick={() => children !== undefined && setExpanded(!expanded)} | |
> | |
{render} | |
</ListCardContainer> | |
{expanded && <ListCardExpandedContainer>{children}</ListCardExpandedContainer>} | |
</Container> | |
); | |
} | |
}; | |
export default React.memo(ListCard); | |
ListCard.propTypes = { | |
children: PropTypes.any, | |
mobileOnly: PropTypes.bool, | |
render: PropTypes.any | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment