22

I just learn react, and want to achieve a function : both A,B are components, if A scroll, then B scroll

The following is my code

<A onScroll="handleScroll"></A>

//what i write now
handleScroll: function(event){
    var target = event.nativeEvent.target;

    //do something to change scrollTop value
    target.scrollTop += 1;

    // it looks the same as not use react
    document.getElementById(B).scrollTop = target.scrollTop;
}

but actually I want my code like this

//what i want
<A scrollTop={this.props.scrollSeed}></A>
<B scrollTop={this.props.scrollSeed}></B>

//...
handleScroll(){
    this.setState({scrollSeed: ++this.state.scrollSeed})
}

it is similar to input

<input value="this.props.value"/>
<input value="this.props.value"/>
<input ref='c' onChange={handleChange}>

//...
handleChange: function() {
    // enter some code in c and then render in a and b automatically
}

In other words, I want some attribute, like scrollTop(different form <input value={}> ,because <A scrollTop={}> doesn't work) ,is bind with some state, so that I can just use setState, and they will update by themselves.

I googled before but can't find the answser. I hope that my poor English won't confuse you.

4 Answers 4

17

There are a number of patterns to achieve this. This sample is what I came up with to get you up and going.

First create a component class which has an oversize element for scroll effect. When dragging the scroll bar, this component calls its handleScroll React property to notify its parent component, with the value of scrollTop.

var Elem = React.createClass({
    render() {
        return (
            <div ref="elem"
                onScroll={ this.onScroll }
                style={{ width: "100px", height: "100px", overflow: "scroll" }}>
                <div style={{ width: "100%", height: "200%" }}>Hello!</div>
            </div>
        );
    },
    componentDidUpdate() {
        this.refs.elem.scrollTop = this.props.scrollTop;
    },
    onScroll() {
        this.props.handleScroll( this.refs.elem.scrollTop );
    }
});

The parent component, aka wrapper, keeps the scroll top value in its state. Its handleScroll is passed to the child components as callback. Any scroll on the child elements triggers the callback, sets the state, results in a redraw, and updates the child component.

var Wrapper = React.createClass({
    getInitialState() {
        return {
            scrollTop: 0
        }
    },
    render() {
        return (
            <div>
                <Elem scrollTop={ this.state.scrollTop } handleScroll={ this.handleScroll } />
                <Elem scrollTop={ this.state.scrollTop } handleScroll={ this.handleScroll } />
            </div>
        );
    },
    handleScroll( scrollTop ) {
        this.setState({ scrollTop });
    }
});

And render the wrapper, presuming an existing <div id="container"></div>.

ReactDOM.render(
    <Wrapper />,
    document.getElementById('container')
);
3
  • 2
    Thanks for you help! And I found that there no need to use ReactDOM.findDOMNode( ), this.refs.elem is enough(and also save 10% usage of my CPU,^_^); Before that, I just try to put my code in componentWillMount, but it shoule be componentDidUpdate;After all, thanks again;
    – edeity
    Nov 17, 2015 at 8:11
  • @edeity, that's very true; revised.
    – Season
    Nov 17, 2015 at 9:05
  • this.refs is deprecated. use reactjs.org/docs/refs-and-the-dom.html#creating-refs Feb 16, 2019 at 8:12
16

2019's answer

First, the fix:

const resetScrollEffect = ({ element }) => {
  element.current.getScrollableNode().children[0].scrollTop = 0
}

const Table = props => {
  const tableRef = useRef(null)
  useEffect(() => resetScrollEffect({ element: tableRef }), [])
  return (
    <Component>
      <FlatList
        ref={someRef}
      />
    </Component>
  )
}

Second, a little explanation:

Idk what is your reason why you got here but I have used flex-direction: column-reverse for my FlatList (it's a list of elements). And I need this property for z-index purposes. However, browsers set their scroll position to the end for such elements (tables, chats, etc.) - this may be useful but I don't need that in my case.

Also, example is shown using React Hooks, but you can use older more traditional way of defining refs

4
  • 1
    I think this is about React Web and your answer applies to React Native. I also wonder how to trigger the effect on click. It seems an effect will be called when loaded and when there's any state or props change. Mar 20, 2019 at 22:31
  • Perhaps rename resetScrollEffect to resetScroll and make the button say onClick={ .resetScroll({ element: tableRef }) }? Mar 20, 2019 at 22:33
  • 3
    @BenjaminAtkin it's a standard to name functions *Effect when it's used for useEffect in react. But the main line corresponding to the question is this element.current.getScrollableNode().children[0].scrollTop = because element.current.scrollTop = in above answer isn't working for me (it was working in some older times) Mar 22, 2019 at 6:51
  • 1
    Thanks man, must have to login and upvote! It's hard to find solution for hooks. element.current.scrollTop works perfectly.
    – Edwardhk
    Feb 13, 2020 at 11:05
7

this.refs is deprecated. use reactjs.org/docs/refs-and-the-dom.html#creating-refs

import React from 'react';

class SomeComponent extends React.Component {
  constructor(props) {
    super(props);
    this.resultsDiv = React.createRef();
  }

  someFunction(){
     this.resultsDiv.current.scrollIntoView({behavior: 'smooth'});

     // alternative:
     // this.resultsDiv.current.scrollTop = 0;
  }

  render() {
    return (
      <div ref={this.resultsDiv} />
    );
  }
}

export default SomeComponent;


1
  • @jimish try this.resultsDiv.current.scrollIntoView({behavior: 'smooth'});. this may not work because of other issues related to css layout, positioning of div. try using this on some other element which you know is positioned with default css. May 29, 2020 at 10:44
2

Here's an updated version of Season's answer, including a runnable snippet. It uses the recommended method for creating refs.

class Editor extends React.Component {
    constructor(props) {
        super(props);
        this.content = React.createRef();
        this.handleScroll = this.handleScroll.bind(this);
    }

    componentDidUpdate() {
        this.content.current.scrollTop = this.props.scrollTop;
    }
    
    handleScroll() {
        this.props.onScroll( this.content.current.scrollTop );
    }

    render() {
        let text = 'a\n\nb\n\nc\n\nd\n\ne\n\nf\n\ng';
        return <textarea
            ref={this.content}
            value={text}
            rows="10"
            cols="30"
            onScroll={this.handleScroll}/>;
    }
}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {scrollTop: 0};
        this.handleScroll = this.handleScroll.bind(this);
    }

    handleScroll(scrollTop) {
        this.setState({scrollTop: scrollTop});
    }

    render() {
        return <table><tbody>
            <tr><th>Foo</th><th>Bar</th></tr>
            <tr>
                <td><Editor
                    scrollTop={this.state.scrollTop}
                    onScroll={this.handleScroll}/></td>
                <td><Editor
                    scrollTop={this.state.scrollTop}
                    onScroll={this.handleScroll}/></td>
            </tr>
        </tbody></table>;
    }
}

ReactDOM.render(
    <App/>,
    document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.