1
0
mirror of https://github.com/kremalicious/portfolio.git synced 2024-06-26 03:06:39 +02:00
portfolio/src/components/molecules/ProjectNav.jsx

110 lines
2.6 KiB
React
Raw Normal View History

2018-11-25 01:52:31 +01:00
import React, { PureComponent } from 'react'
2018-04-16 22:32:30 +02:00
import PropTypes from 'prop-types'
2018-06-22 18:54:29 +02:00
import { Link, graphql, StaticQuery } from 'gatsby'
2018-05-04 01:58:43 +02:00
import Img from 'gatsby-image'
2019-11-25 13:46:44 +01:00
import shortid from 'shortid'
2018-06-11 19:48:38 +02:00
import styles from './ProjectNav.module.scss'
2018-04-16 22:32:30 +02:00
const query = graphql`
query {
allProjectsYaml {
edges {
node {
title
slug
img {
childImageSharp {
fluid(maxWidth: 500, quality: 85) {
...GatsbyImageSharpFluid_noBase64
}
}
}
}
}
}
}
`
2019-11-25 13:46:44 +01:00
const Project = ({ node, refCurrentItem }) => (
<div className={styles.item} ref={refCurrentItem}>
<Link className={styles.link} to={node.slug}>
<Img
className={styles.image}
fluid={node.img.childImageSharp.fluid}
alt={node.title}
/>
<h1 className={styles.title}>{node.title}</h1>
</Link>
</div>
)
Project.propTypes = {
node: PropTypes.any.isRequired,
refCurrentItem: PropTypes.any
}
2018-11-25 01:52:31 +01:00
export default class ProjectNav extends PureComponent {
static propTypes = {
currentSlug: PropTypes.string.isRequired
}
2018-09-06 14:28:01 +02:00
state = {
scrollLeftPosition: 0
}
scrollContainer = React.createRef()
currentItem = React.createRef()
componentDidMount() {
this.scrollToCurrent()
}
componentDidUpdate() {
this.scrollToCurrent()
2018-06-23 16:31:08 +02:00
}
scrollToCurrent = () => {
const scrollContainer = this.scrollContainer.current
const activeItem = this.currentItem.current
const scrollRect = scrollContainer.getBoundingClientRect()
2019-11-25 13:46:44 +01:00
const activeRect = activeItem && activeItem.getBoundingClientRect()
const scrollLeftPosition =
2019-11-25 13:46:44 +01:00
activeRect &&
activeRect.left -
2019-11-25 13:46:44 +01:00
scrollRect.left -
scrollRect.width / 2 +
activeRect.width / 2
scrollContainer.scrollLeft += this.state.scrollLeftPosition
2019-03-29 23:43:40 +01:00
this.setState({ scrollLeftPosition })
}
render() {
const { currentSlug } = this.props
return (
<StaticQuery
query={query}
2018-06-22 18:54:29 +02:00
render={data => {
const projects = data.allProjectsYaml.edges
2018-06-12 11:16:17 +02:00
return (
<nav className={styles.projectNav} ref={this.scrollContainer}>
2019-03-29 23:43:40 +01:00
{projects.map(({ node }) => {
const isCurrent = node.slug === currentSlug
return (
2019-11-25 13:46:44 +01:00
<Project
key={shortid.generate()}
2019-03-29 23:43:40 +01:00
node={node}
refCurrentItem={isCurrent ? this.currentItem : null}
/>
)
})}
2018-10-17 20:26:08 +02:00
</nav>
2018-06-12 11:16:17 +02:00
)
2018-06-22 18:54:29 +02:00
}}
/>
)
}
}