Sadia1990
Sadia1990

Reputation: 97

Using react-sticky to make a sticky header

I am trying to use the react-sticky package to make a sticky header, but my header keeps scrolling out of view. This is the package: https://www.npmjs.com/package/react-sticky I am not sure if I am using the StickyContainer or Sticky compnents correctly. I am actually a bit confused about the "style" prop you're supposed to pass to the Sticky container.

If anyone can help, will be much appreciated. Thanks!

Here's the code for App.js:

import React, { Component } from 'react';
import './App.css';
import Header from './components/Header';
import Footer from './components/Footer';
import HomePage from './components/pages/HomePage';
import OurWork from './components/pages/OurWork';
import ContactUs from './components/pages/ContactUs';
import { BreakpointProvider } from 'react-socks';
import { StickyContainer, Sticky } from "react-sticky";
import { setDefaultBreakpoints } from 'react-socks';

setDefaultBreakpoints([
  { small: 0 },
  { medium: 700 }
]);

class App extends Component {
  pageStyle = {
    display: 'flex',
    flexDirection: 'column'
  }

  render() {
    return (
      <BreakpointProvider>
        <StickyContainer>
          <div className="App">
            <Sticky>
              {({style}) => <Header style={style}/>}
            </Sticky>
            <div className="page" style={this.pageStyle}>
                <HomePage />
              <OurWork />
              <ContactUs />
            </div>
          <Footer />
        </div>
        </StickyContainer>
      </BreakpointProvider>
    );
  }
}

export default App;

Here is the Header component:

import React, { Component } from 'react';
import Logo from './Logo'
import NavBar from './NavBar';
import logo from '../images/transparent.png';

class Header extends Component {
    headerStyle = {
        height: 100,
        margin: 20,
        display: 'flex',
        justifyContent: 'space-between',
        zIndex: 10
    };

    render() {
        return (
            <div className="header" style={this.headerStyle}>
                <Logo logo={logo}/>
                <NavBar />
            </div>
        );
    }

};

export default Header;

Upvotes: 1

Views: 11887

Answers (1)

OnlyJS
OnlyJS

Reputation: 317

No external library is required for sticky header, check this resource React Table Sticky Header without external library

Demo

enter image description here

The trick is like

1 . divide the header and data part

  1. Use fixed width for both

  2. Wrap data container with a div , give that container div a fixed height, allow

    .container { overflox-y : scroll; height: 300px; }

Upvotes: 3

Related Questions