简体   繁体   中英

React scroll element into view

I am rendering a calendar component, which is again rendering a Month component based on a months array:

{
  months.map(month =>
   <div style={{marginBottom: "35px"}} key={month}>
     <Month
       monthName={this.renderMonthName(month)}
       daysOfMonth={Object.keys(calendarDays).filter(day => new Date(day).getMonth() === month)}
       calendarDays={calendarDays}
       year={this.state.year}
     />
   </div>
  )
}

The result is a long list of single months:

在此处输入图片说明

However, what I want is that once the calendar component is rendered it should scroll to the current month (otherwise users have to scroll down manually to the current month).

I know about refs in React but I'm no sure how to apply this here. Is there a way to scroll to, let's say, eg the key of each rendered Month component?

Best answer that doesn't need nitty gritty Javascript code is answer from this question

https://stackoverflow.com/a/49842367/3867490

You can hook it up at the componentDidMount hook of your react app so it will only run whenever the component was mounted.

Code is here, might be ugly but you can get the idea from here.

class Hello extends React.Component {
    constructor(props){
    super(props);
    this.IsCurrentMonth = this.IsCurrentMonth.bind(this);
    this.ScrollToCurrentMonth = this.ScrollToCurrentMonth.bind(this);
        this.state = {
        months: ['January', 'February','March', 'April', 'May', 'June', 'July', 'August','September', 'October', 'November', 'December'],
      currentMonth :  new Date().getMonth(),
    }  
  }

  componentDidMount(){
    this.ScrollToCurrentMonth();
  }
  IsCurrentMonth(toCompare){
    if(this.state.currentMonth === toCompare){
        return 'calendar_active';
    }
    return;

  }

  ScrollToCurrentMonth(){
  var myElement = document.getElementsByClassName('calendar_active')[0];
    const y = myElement.getBoundingClientRect().top + window.scrollY;
window.scroll({
  top: y,
  behavior: 'smooth'
});  

  }

  render() {
    return (
    <div className={this.state.currentMonth}>
    {
    this.state.months.map((month, index) =>{

            return <div className={`month ${this.IsCurrentMonth(index)}`  }>{month}</div>
    })


    }

</div>

    );
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

See the working fiddle here https://jsfiddle.net/keysl183/f9ohzymd/31/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM