1

I can't get react-spring to work. I'm fairly new to this so I have no idea what is going wrong. I'm trying to make navbar appear from top to bottom to 40vh, but it doesn't appear to be recognizing the props passed. I used create-react-app and react-spring 8.0.27

App.js:

const App = () => {
  const [open, setOpen] = useState(false);

  const navprops = useSpring({
    from: {height: "0"},
    to: {height: "40vh"}
  })

  return (
    <Fragment>
      {open ? <Navbar style={navprops}/> : null}
    </Fragment>

Navbar.js:


const NavBar = styled(animated.nav)`
  width: 100%;
`;

const Navbar = (props) => {
  return (
    <NavBar style={props.style}>
    </NavBar>
  );
};

This is basically the code. There are more style props but I guess it's irrelevant to functionality.

animated and useSpring are imported in both files for testing. Thank you for your help.

Gautam Naik
  • 8,990
  • 3
  • 27
  • 42

1 Answers1

1

Here is my solution,

Demo Link

Navbar.js

import React from "react";
import styled from "styled-components";
import { animated } from "react-spring";

const NavBar = styled(animated.nav)`
  width: 100%;
  background: red;
`;

export default (props) => {
  return <NavBar style={props.style}></NavBar>;
};

App.js

import React, { useState } from "react";
import { useTransition, config } from "react-spring";
import Navbar from "./Navbar";

export default function App() {
  const [open, setOpen] = useState(false);

  // const navprops = useSpring({
  //   from: { height: "0" },
  //   to: { height: "40vh" },
  //   config: config.wobbly
  // });

  const transitions = useTransition(open, null, {
    initial: { height: "0px" }, //Not required
    from: { height: "0px" },
    enter: { height: "40vh" },
    leave: { height: "0px" },
    config: config.wobbly //More configs here https://www.react-spring.io/docs/hooks/api
  });

  return (
    <div className="App">
      {transitions.map(
        ({ item, key, props }) => item && <Navbar key={key} style={props} />
      )}
      <br />
      <br />
      <button onClick={() => setOpen(!open)}>Toggle Navbar</button>
    </div>
  );
}

I do not think useSpring will work on unmounted component. You were trying to animate an unmounted component.

According to documentation, useTransition can be used to animate mounting of unmounted components.

The syntax is little complicated, but they have made the syntax simpler in version 9(release candidate) of react-spring Link Here

Gautam Naik
  • 8,990
  • 3
  • 27
  • 42