Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import React, { useState } from 'react'
  2.  
  3. // this component will be the focus of this series
  4. // we will extend its functionality considerably throughout
  5.  
  6. // for now let's just setup the translations...
  7.  
  8. function Pager({ children, activeIndex }) {
  9. // this will update when the activeIndex changes
  10. // try updating activeIndex in devtools and see how the blue container changes position
  11. const offset = activeIndex * 100 * -1
  12.  
  13. return (
  14. <div
  15. style={{
  16. border: 'thin solid blue',
  17. position: 'relative',
  18. height: '100%',
  19. width: '100%',
  20. transform: `translateX(${offset}%)`,
  21. }}>
  22. {React.Children.map(children, (element, index) => {
  23. return (
  24. <div
  25. style={{
  26. ...absoluteFill,
  27. transform: `translateX(${index * 100}%)`,
  28. }}>
  29. {element}
  30. </div>
  31. )
  32. })}
  33. </div>
  34. )
  35. }
  36.  
  37. const absoluteFill = {
  38. position: 'absolute',
  39. left: 0,
  40. right: 0,
  41. bottom: 0,
  42. top: 0,
  43. }
  44.  
  45. const PAGE_SIZE = 200
  46.  
  47. // this will represent a consumer component or any part of your application
  48. function App() {
  49. // all we need to pass are children and an activeIndex prop to our pager component
  50. const [activeIndex, setActiveIndex] = useState(0)
  51.  
  52. const children = Array.from({ length: 10 }).map((c, i) => (
  53. <h1 key={i} style={{ textAlign: 'center' }}>
  54. Index {i}
  55. </h1>
  56. ))
  57.  
  58. return (
  59. <div>
  60. <div
  61. style={{
  62. width: PAGE_SIZE,
  63. height: PAGE_SIZE,
  64. display: 'flex',
  65. margin: 'auto',
  66. padding: '5px',
  67. border: 'thin solid red',
  68. }}>
  69. <Pager activeIndex={activeIndex}>{children}</Pager>
  70. </div>
  71.  
  72. <div
  73. style={{
  74. display: 'flex',
  75. flexDirection: 'column',
  76. alignItems: 'center',
  77. justifyContent: 'space-around',
  78. }}>
  79. <strong style={{ margin: '5px 0' }}>activeIndex: {activeIndex}</strong>
  80. <button
  81. style={{ margin: '5px 0' }}
  82. onClick={() => setActiveIndex(activeIndex + 1)}>
  83. Increment
  84. </button>
  85. <button
  86. style={{ margin: '5px 0' }}
  87. onClick={() => setActiveIndex(activeIndex - 1)}>
  88. Decrement
  89. </button>
  90. </div>
  91. </div>
  92. )
  93. }
  94.  
  95. export default App
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement