Following this tutorial I am trying to implement a similar component using typescript.
My Component:
import React, { Component } from "react";
import TransitionGroup from "react-addons-transition-group";
import { TweenMax } from "gsap";
import { tableOfContentsData } from "../mockData/tableOfContents";
import { Chapter } from "../types/data/tableOfContents";
import styled from "styled-components";
import { pallete } from "../constants/pallete";
type State = {
isExpanded: boolean;
};
const StyledContainer = styled.div`
position: fixed;
top: 0;
left: 0;
padding: 1em;
background-color: ${pallete.primary};
color: ${pallete.text};
font-size: 16px;
height: 100vh;
max-width: 200px;
.chapter-link {
min-height: 24px;
min-width: 54px;
margin-bottom: 1em;
}
.close-btn {
background-color: ${pallete.secondary};
position: absolute;
top: 0;
right: -54px;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
width: 54px;
}
`;
class TableOfContents extends Component<{}, State> {
state = {
isExpanded: true
};
toggleExpanded = (): void => {
this.setState({
isExpanded: !this.state.isExpanded
});
};
render() {
return (
<StyledContainer>
<TransitionGroup>
{this.state.isExpanded && <ChaptersList />}
</TransitionGroup>
<div className="close-btn" onClick={this.toggleExpanded}>
<
</div>
</StyledContainer>
);
}
}
class ChaptersList extends Component {
componentWillEnter(callback: any) {
const el = (this as any).container;
TweenMax.fromTo(
el,
0.3,
{ x: -100, opacity: 0 },
{ x: 0, opacity: 1, onComplete: callback }
);
}
componentWillLeave(callback: any) {
const el = (this as any).container;
TweenMax.fromTo(
el,
0.3,
{ x: 0, opacity: 1 },
{ x: -100, opacity: 0, onComplete: callback }
);
}
render() {
return (
<div>
{tableOfContentsData.map((chapter: Chapter, i: number) => (
<div key={i} className="chapter-link">
{chapter.title}
</div>
))}
</div>
);
}
}
export default TableOfContents;
When I click the .close-btn
div I get the following error:
uncaught exception: Cannot tween a null target.
One of the possible errors I found during googling is the TweenMax
import, but if I try to import it from gsap/TweenMax
, ts complains about missing type definitions (I have @types/gsap
installed).
You aren't currently doing anything in ChaptersList
to set this.container
, so el
will be undefined. This should be handled via a ref
on the outermost div
.
The render
of ChaptersList
should look like:
render() {
return (
<div ref={c => (this as any).container = c}>{/* this is the change */}
{tableOfContentsData.map((chapter: Chapter, i: number) => (
<div key={i} className="chapter-link">
{chapter.title}
</div>
))}
</div>
);
}