chow1340
chow1340

Reputation: 13

Passing variable from one function to another

I am trying to pass the variable 'styles' down to the the style = {styles}. How might I go about doing this?

function Header() {
    var prevScrollpos = window.pageYOffset;
    var currentScrollpos = window.pageYOffset
    window.onscroll = function () {
        if (prevScrollpos > currentScrollpos){
            var styles = {
                top: '0'
            }
        } else {
            var styles = {
                top: '-100px'
            }
        }
    }


    return (
        <div className = 'navbar' style = {styles}>
            <div id = 'mainButtons' >
                    <button id = 'projects'> PROJECTS </button>
                    <button id = 'about'> ABOUT </button>
                    <button id = 'contact'> CONTACT </button>
                    <button id = 'resume'> RESUME </button>

            </div>
        </div>
         )

Upvotes: 0

Views: 67

Answers (2)

Vishal Bhatia
Vishal Bhatia

Reputation: 71

If you do not want to use state(which you should not if something can be rather passed as props), you could do this

function Header() {
    const styles = {};
    const updateStyle = top => {
        styles.top = top;
    };

window.onscroll = function() {
    if (prevScrollpos > currentScrollpos) {
        updateStyle(0);
    } else {
        updateStyle(-100);
    }
};

return (
    <div className="navbar" style={styles}>
        <div id="mainButtons">
            <button id="projects"> PROJECTS </button>
            <button id="about"> ABOUT </button>
            <button id="contact"> CONTACT </button>
            <button id="resume"> RESUME </button>
        </div>
    </div>
);

}

Upvotes: 1

wentjun
wentjun

Reputation: 42516

Since you are working with functional components, you could try using React Hooks and store it as part of your component's State Hook. Do note that react hooks are only added on React 16.8.

function Header() {
  const [headerStyle, setHeaderStyle] = useState({
    top: '0',
  });

  window.onscroll = function () {
    if (prevScrollpos > currentScrollpos){
      setHeaderStyle({
        top: '0',
      });
     } else {
       setHeaderStyle({
         top: '-100px',
       });
      }
  }

  return (
    <div className = 'navbar' style = {styles}>
      <div id = 'mainButtons' >
        <button id = 'projects'> PROJECTS </button>
        <button id = 'about'> ABOUT </button>
        <button id = 'contact'> CONTACT </button>
        <button id = 'resume'> RESUME </button>
      </div>
    </div>
  )


}

Upvotes: 3

Related Questions