react-scroll#animateScroll JavaScript Examples

The following examples show how to use react-scroll#animateScroll. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MessengerContent.js    From social-network with MIT License 6 votes vote down vote up
scrollToBottom() {
    //console.log(this.messagesContainer.current.scrollHeight);

    if (
      this.messagesContainer.current.scrollHeight -
        this.messagesContainer.current.scrollTop -
        this.messagesContainer.current.clientHeight <
      350
    ) {
      animateScroll.scrollToBottom({
        containerId: "ContainerElementID",
        duration: 200,
        delay: 0
      });
    }
  }
Example #2
Source File: useSmoothScrollTo.jsx    From gatsby-startbootstrap-agency with MIT License 6 votes vote down vote up
useSmoothScrollTo = (anchorOrPosition, options = {}) => {
  const opts = React.useMemo(
    () => ({
      ...DefOptions,
      ...options,
    }),
    [options],
  );

  const handleScrollTo = React.useCallback(() => {
    switch (typeof anchorOrPosition) {
      case "number":
      case "bigint":
        animateScroll.scrollTo(anchorOrPosition, opts);
        break;
      case "string":
        scroller.scrollTo(anchorOrPosition, opts);
        break;
      default:
        break;
    }
  }, [anchorOrPosition, opts]);

  return handleScrollTo;
}
Example #3
Source File: WTCode.js    From walkthru with MIT License 6 votes vote down vote up
function scrollNewCenter(center, el) {
  const codeEl = el.firstChild
  const count = codeEl.querySelectorAll('.__line-no').length
  if (count > 1) {
    const lineHeight = codeEl.offsetHeight / count
    const scrollPos = lineHeight * center - el.offsetHeight / 2
    animateScroll.scrollTo(scrollPos, {
      containerId: 'scrollContainer',
      duration: 500,
    })
  }
}
Example #4
Source File: BlogPostPage.js    From TimesOfInternet with MIT License 5 votes vote down vote up
export default function BlogPostPage() {
  const [newsArticles, setNewsArticles] = useState([]);
  const [activeArticle, setActiveArticle] = useState(-1);

  const alanKey = process.env.REACT_APP_ALAN_KEY;

  const askButtonHandler = () => {
    animateScroll.scrollTo(850);
    alanBtn({
      key: alanKey,
      onCommand: ({ command, articles, number }) => {
        if (command === "newHeadlines") {
          setNewsArticles(articles);
          setActiveArticle(-1);
        } else if (command === "highlight") {
          setActiveArticle(prevActiveArticle => prevActiveArticle + 1);
        } else if (command === "open") {
          const parsedNumber =
            number.length > 2 ? wordToNumbers(number, { fuzzy: true }) : number;
          const article = articles[parsedNumber - 1];

          if (parsedNumber > 20) {
            alanBtn().playText("Please try that again.");
          } else if (article) {
            window.open(article.url, "_blank");
            alanBtn().playText("Opening...");
          }
        }
      }
    }).activate();
  };

  const classes = useStyles();
  return (
    <div>
      <Header
        links={<HeaderLinks dropdownHoverColor="dark" />}
        fixed
        color="transparent"
        changeColorOnScroll={{
          height: 300,
          color: "light"
        }}
      />
      <Parallax image={require("assets/img/bg4.jpg")}>
        <div className={classes.container}>
          <GridContainer>
            <GridItem xs={12} sm={6} md={6}>
              <h1 className={classes.title}>Your Story Starts With Us.</h1>
              <h4 className={classes.subtitle}>
                Voice controlled web application created using ReactJs, styled
                with Material-UI and integerated with Alan-AI for your voice
                commands. Get the latest news around the world. All you need to
                do is,
              </h4>
              <br />
              <Button color="danger" size="lg" onClick={askButtonHandler}>
                <i className="fas fa-play" />
                Just Ask
              </Button>
            </GridItem>
          </GridContainer>
        </div>
      </Parallax>
      <div className={classes.main}>
        <div className={classes.container}>
          <SectionSimilarStories
            articles={newsArticles}
            activeArticle={activeArticle}
          />
        </div>
      </div>
      <FooterContent />
    </div>
  );
}
Example #5
Source File: SectionSimilarStories.js    From TimesOfInternet with MIT License 5 votes vote down vote up
export default function SectionSimilarStories({ articles, activeArticle }) {
  const classes = useStyles();

  useEffect(() => {
    if (articles.length) animateScroll.scrollTo(850);
  }, [articles]);

  if (!articles.length) {
    return (
      <div className={classes.section}>
        <div className={classes.container}>
          <GridContainer>
            <GridItem md={12}>
              <h2 className={classes.title + " " + classes.textCenter}>
                Few examples to ask for
              </h2>
              <br />
              <GridContainer>
                {infoCards.map((infoCard) => (
                  <GridItem xs={12} sm={6} md={6}>
                    <Card
                      raised
                      background
                      style={{ backgroundImage: "url(" + office2 + ")" }}
                    >
                      <CardBody background>
                        <h3 className={classes.cardTitle}>{infoCard.title}</h3>
                        {infoCard.info ? (
                          <h5>
                            {infoCard.title.split(" ")[2]}: {infoCard.info}
                          </h5>
                        ) : null}
                        <h4 className={classes.category}>
                          <b style={{ fontWeight: 400 }}>Try saying:</b>{" "}
                          {infoCard.text}
                        </h4>
                      </CardBody>
                    </Card>
                  </GridItem>
                ))}
              </GridContainer>
            </GridItem>
          </GridContainer>
        </div>
      </div>
    );
  }
  return (
    <div className={classes.section}>
      <div className={classes.container}>
        <GridContainer>
          <GridItem md={12}>
            <h2 className={classes.title + " " + classes.textCenter}>
              The News you asked for
            </h2>
            <br />
            <GridContainer>
              {articles.map((article, i) => (
                <GridItem xs={12} sm={4} md={4}>
                  <NewsCard
                    article={article}
                    i={i}
                    activeArticle={activeArticle}
                  />
                </GridItem>
              ))}
            </GridContainer>
          </GridItem>
        </GridContainer>
      </div>
    </div>
  );
}
Example #6
Source File: SideBarHeading.jsx    From intergalactic with MIT License 5 votes vote down vote up
function SideBarHeading({ headings }) {
  const { pathname } = useLocation();
  const [activeId, setActiveId] = React.useState();

  React.useEffect(() => {
    setActiveId(headings.length ? headings[0].id : undefined);
    const links = headings.map((heading) => document.querySelector(`#${heading.id}`)).reverse();
    const handleScroll = trottle(() => {
      const scrollCenter =
        document.scrollingElement.scrollTop + document.documentElement.clientHeight / 2;
      const linkReversedIndex = links.findIndex((link) => scrollCenter > link.offsetTop);
      if (linkReversedIndex !== -1)
        setActiveId(headings[headings.length - 1 - linkReversedIndex]?.id);
    });
    document.addEventListener('scroll', handleScroll);
    return () => document.removeEventListener('scroll', handleScroll);
  }, [pathname, headings]);

  return (
    <>
      <div className={styles.sideBarWrapper}>
        {headings.map((heading) => (
          <Link
            className={cx(styles.navLink, heading.id === activeId && styles.navLinkActive)}
            key={heading.html}
            to={heading.id}
            smooth={true}
            offset={-140}
            duration={200}
            delay={0}
          >
            {heading.html}
          </Link>
        ))}
      </div>
      <span className={styles.buttonUp} onClick={() => animateScroll.scrollToTop({ smooth: true })}>
        <ArrowUpM interactive />
      </span>
    </>
  );
}
Example #7
Source File: WTCode.js    From walkthru with MIT License 4 votes vote down vote up
function WTCode({ files, step, sameFile, config }) {
  const { focus, language, center } = step.frontmatter
  const ref = useRef()
  const active = step.frontmatter.file
  const [content, setContent] = useState('')
  const [prevScrollPos, setPrevScrollPos] = useState(0)
  const file = files.find((file) => file.path === active)
  const [activeFile, setActiveFile] = useState(file)
  const highlightedLines = focus ? getHighlightedLines(focus.toString()) : []
  useEffect(() => {
    const file = files.find((file) => file.path === active)
    setActiveFile(file)
  }, [files, step, active])
  useEffect(() => {
    let scrollPos = 0
    if (sameFile) {
      animateScroll.scrollTo(prevScrollPos, {
        containerId: 'scrollContainer',
        duration: 0,
      })
      scrollPos = ref.current.scrollTop
    }
    scrollNewCenter(center, ref.current)
    setPrevScrollPos(scrollPos)
  }, [content, center, prevScrollPos, sameFile])
  useEffect(() => {
    ref.current.scrollTo(0, 0)
  }, [])
  return (
    <>
      <WTFileBar files={files} activeFile={activeFile} config={config} />
      <Highlight
        {...defaultProps}
        theme={theme}
        code={activeFile.content}
        language={language || activeFile.path.split('.').pop()}
      >
        {({ className, style, tokens, getLineProps, getTokenProps }) => {
          return (
            <Pre
              ref={ref}
              className={`${className} ${
                highlightedLines.length ? '' : 'no-highlight'
              }`}
              id="scrollContainer"
            >
              <Code>
                <LineNumbers>
                  {tokens.map((line, i) => {
                    const lineProps = getLineProps({ line, key: i })
                    if (highlightedLines.indexOf(i + 1) > -1) {
                      lineProps.highlighted = true
                    }
                    return (
                      <div
                        style={lineProps.style}
                        key={`number-wrapper-${i.toString()}`}
                      >
                        <LineNumber
                          highlighted={lineProps.highlighted}
                          className="__line-no"
                          key={`number-${i.toString()}`}
                        >
                          {i + 1}
                        </LineNumber>
                      </div>
                    )
                  })}
                </LineNumbers>
                <Lines>
                  {tokens.map((line, i) => {
                    const lineProps = getLineProps({ line, key: i })
                    if (highlightedLines.indexOf(i + 1) > -1) {
                      lineProps.highlighted = true
                    }
                    return (
                      <Line {...lineProps} key={i.toString()}>
                        <LineContent key={`content-${i.toString()}`}>
                          {line.map((token, key) => {
                            const tokenProps = getTokenProps({ token, key })
                            if (highlightedLines.indexOf(i + 1) > -1) {
                              tokenProps.highlighted = true
                            }
                            return <Token {...tokenProps} key={`${i}-${key}`} />
                          })}
                        </LineContent>
                      </Line>
                    )
                  })}
                </Lines>
              </Code>
            </Pre>
          )
        }}
      </Highlight>
    </>
  )
}