Affix

Wrap Affix around another component to make it stick the viewport.

When To Use#

On longer web pages, its helpful for some content to stick to the viewport. This is common for menus and actions.

Please note that Affix should not cover other content on the page, especially when the size of the viewport is small.

Examples


The simplest usage.

expand codeexpand code
import React, { useState } from 'react';
import { Affix, Button } from 'antd';

const Demo: React.FC = () => {
  const [top, setTop] = useState(10);
  const [bottom, setBottom] = useState(10);

  return (
    <>
      <Affix offsetTop={top}>
        <Button type="primary" onClick={() => setTop(top + 10)}>
          Affix top
        </Button>
      </Affix>
      <br />
      <Affix offsetBottom={bottom}>
        <Button type="primary" onClick={() => setBottom(bottom + 10)}>
          Affix bottom
        </Button>
      </Affix>
    </>
  );
};

ReactDOM.render(<Demo />, mountNode);

Set a target for 'Affix', which is listen to scroll event of target element (default is window).

expand codeexpand code
import React, { useState } from 'react';
import { Affix, Button } from 'antd';

const Demo: React.FC = () => {
  const [container, setContainer] = useState(null);
  return (
    <div className="scrollable-container" ref={setContainer}>
      <div className="background">
        <Affix target={() => container}>
          <Button type="primary">Fixed at the top of container</Button>
        </Affix>
      </div>
    </div>
  );
};

ReactDOM.render(<Demo />, mountNode);

Callback with affixed state.

expand codeexpand code
import { Affix, Button } from 'antd';

ReactDOM.render(
  <Affix offsetTop={120} onChange={affixed => console.log(affixed)}>
    <Button>120px to affix top</Button>
  </Affix>,
  mountNode,
);

API#

PropertyDescriptionTypeDefault
offsetBottomOffset from the bottom of the viewport (in pixels)number-
offsetTopOffset from the top of the viewport (in pixels)number0
onChangeCallback for when Affix state is changedfunction(affixed)-
targetSpecifies the scrollable area DOM node() => HTMLElement() => window

Note: Children of Affix must not have the property position: absolute, but you can set position: absolute on Affix itself:

<Affix style={{ position: 'absolute', top: y, left: x }}>...</Affix>

FAQ#

Affix bind container with target, sometime move out of container.#

We don't listen window scroll for performance consideration. You can add listener if you still want: https://codesandbox.io/s/2xyj5zr85p

Related issues:#3938 #5642 #16120

SpaceBreadcrumb