Created
August 10, 2019 19:29
-
-
Save ajsmth/3ef238644ca7213bdaf8deb0e55c8641 to your computer and use it in GitHub Desktop.
Pager Component -- Initial Setup
This file contains 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 React, { useState } from 'react' | |
// this component will be the focus of this series | |
// we will extend its functionality considerably throughout | |
// for now let's just setup the translations... | |
function Pager({ children, activeIndex }) { | |
// this will update when the activeIndex changes | |
// try updating activeIndex in devtools and see how the blue container changes position | |
const offset = activeIndex * 100 * -1 | |
return ( | |
<div | |
style={{ | |
border: 'thin solid blue', | |
position: 'relative', | |
height: '100%', | |
width: '100%', | |
transform: `translateX(${offset}%)`, | |
}}> | |
{React.Children.map(children, (element, index) => { | |
return ( | |
<div | |
style={{ | |
...absoluteFill, | |
transform: `translateX(${index * 100}%)`, | |
}}> | |
{element} | |
</div> | |
) | |
})} | |
</div> | |
) | |
} | |
const absoluteFill = { | |
position: 'absolute', | |
left: 0, | |
right: 0, | |
bottom: 0, | |
top: 0, | |
} | |
const PAGE_SIZE = 200 | |
// this will represent a consumer component or any part of your application | |
function App() { | |
// all we need to pass are children and an activeIndex prop to our pager component | |
const [activeIndex, setActiveIndex] = useState(0) | |
const children = Array.from({ length: 10 }).map((c, i) => ( | |
<h1 key={i} style={{ textAlign: 'center' }}> | |
Index {i} | |
</h1> | |
)) | |
return ( | |
<div> | |
<div | |
style={{ | |
width: PAGE_SIZE, | |
height: PAGE_SIZE, | |
display: 'flex', | |
margin: 'auto', | |
padding: '5px', | |
border: 'thin solid red', | |
}}> | |
<Pager activeIndex={activeIndex}>{children}</Pager> | |
</div> | |
<div | |
style={{ | |
display: 'flex', | |
flexDirection: 'column', | |
alignItems: 'center', | |
justifyContent: 'space-around', | |
}}> | |
<strong style={{ margin: '5px 0' }}>activeIndex: {activeIndex}</strong> | |
<button | |
style={{ margin: '5px 0' }} | |
onClick={() => setActiveIndex(activeIndex + 1)}> | |
Increment | |
</button> | |
<button | |
style={{ margin: '5px 0' }} | |
onClick={() => setActiveIndex(activeIndex - 1)}> | |
Decrement | |
</button> | |
</div> | |
</div> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment