ReactJS how to scroll to an element
I have a chat widget that pulls up an array of messages everytime I scroll up. The problem I am facing now is, the slider stays fixed at the top when messages load, I want it to focus on the last index element from the previous array. I figured out that i can make dynamic refs by passing index, but I would also need to know what kind of scroll function to use to achieve that
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
//scroll to testNode
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
javascript reactjs ecmascript-6
add a comment |
I have a chat widget that pulls up an array of messages everytime I scroll up. The problem I am facing now is, the slider stays fixed at the top when messages load, I want it to focus on the last index element from the previous array. I figured out that i can make dynamic refs by passing index, but I would also need to know what kind of scroll function to use to achieve that
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
//scroll to testNode
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
javascript reactjs ecmascript-6
For a bundled solution: npmjs.com/package/react-scroll-to-component
– tokland
Dec 21 '17 at 11:00
add a comment |
I have a chat widget that pulls up an array of messages everytime I scroll up. The problem I am facing now is, the slider stays fixed at the top when messages load, I want it to focus on the last index element from the previous array. I figured out that i can make dynamic refs by passing index, but I would also need to know what kind of scroll function to use to achieve that
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
//scroll to testNode
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
javascript reactjs ecmascript-6
I have a chat widget that pulls up an array of messages everytime I scroll up. The problem I am facing now is, the slider stays fixed at the top when messages load, I want it to focus on the last index element from the previous array. I figured out that i can make dynamic refs by passing index, but I would also need to know what kind of scroll function to use to achieve that
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
//scroll to testNode
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
javascript reactjs ecmascript-6
javascript reactjs ecmascript-6
asked Apr 16 '17 at 20:33
edmamertoedmamerto
87421430
87421430
For a bundled solution: npmjs.com/package/react-scroll-to-component
– tokland
Dec 21 '17 at 11:00
add a comment |
For a bundled solution: npmjs.com/package/react-scroll-to-component
– tokland
Dec 21 '17 at 11:00
For a bundled solution: npmjs.com/package/react-scroll-to-component
– tokland
Dec 21 '17 at 11:00
For a bundled solution: npmjs.com/package/react-scroll-to-component
– tokland
Dec 21 '17 at 11:00
add a comment |
9 Answers
9
active
oldest
votes
Option 1: Use React.createRef (React 16.3 +)
class MyComponent extends Component {
constructor(props) {
super(props)
this.myRef = React.createRef() // Create a ref object
}
render() {
return <div ref={this.myRef}></div>
} // attach the ref property to a dom element
scrollToMyRef = () => window.scrollTo(0, this.myRef.current.offsetTop)
// run this method to execute scrolling.
}
Option 2: Use a ref callback
class MyComponent extends Component {
constructor(props){ // Optional, declare a class field to improve readability
super(props)
this.myRef=null
}
render() {
return <div ref={ (ref) => this.myRef=ref }></div>
} // Attach the dom element to a class field
scrollToMyRef = () => window.scrollTo(0, this.myRef.offsetTop)
// run this method to execute scrolling.
}
Don't use String refs.
String refs harm performance, aren't composable, and are on there way out (Aug 2018).
string refs have some issues, are considered legacy, and are likely to
be removed in one of the future releases. [Official React documentation]
resource1, resource2
Principles
- A ref can only be stored in a class component. (this will change in the future when the ref hook is released)
- In order to scroll to an element, the ref property in the class must be attached to an actual dom element; We are using the browser's native scrolling method, and we need to know the actual position of the element on the page.
- A ref (in either of the methods suggested above) can be passed on to a child as a prop.
Passing ref to a child
React.createRef - Pass the ref object as a prop to the child component.
render() {
return <ChildComp refProp={this.myRef}></ChildComp>
}
Then attach the ref prop to a dom element.
class ChildComp extends Component {
render () {
return <div ref={this.props.refProp} />
}
}
Update
In the past I recommended passing an options object to window.scrollTo. Edge and iOS don't support this form yet.
2
window.scrollTo(0, offsetTop)is a better option with better support among current browsers
– MoMo
Oct 2 '18 at 11:10
1
Could make sure you are consistent in your exemple. We're starting from myRef, going with domRef, and ending with tesNode ?. That is quite confusing
– Louis Lecocq
Oct 2 '18 at 12:42
1
@LouisLecocq, I value your feedback. I renamed variables for consistency. Thanks
– Ben Carp
Oct 2 '18 at 13:23
2
Obvious after the fact, but it is important to mention that this only works for native DOM elements and not just any React component.
– jpunk11
Nov 1 '18 at 19:19
2
@SimonFranzen Take a look at my updated answer - TLDR - class component case. When scrollToMyRef is called it will scroll to the child you attached the ref to. You can pass the method to a different child component, and trigger it from there.
– Ben Carp
Nov 8 '18 at 17:28
|
show 5 more comments
Just find the top position of the element you've already determined https://www.w3schools.com/Jsref/prop_element_offsettop.asp then scroll to this position via scrollTo method https://www.w3schools.com/Jsref/met_win_scrollto.asp
Something like this should work:
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
window.scrollTo(0, tesNode.offsetTop);
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
UPDATE:
since React v16.3 the React.createRef() is preferred
constructor(props) {
super(props);
this.myRef = React.createRef();
}
handleScrollToElement(event) {
if (<some_logic>){
window.scrollTo(0, this.myRef.current.offsetTop);
}
}
render() {
return (
<div>
<div ref={this.myRef}></div>
</div>)
}
1
This is the better answer. UsingReactDOM.findDomNode()is better practice - since React re-renders components, a div that you simply get by its ID might not exist by the time you call the function
– Good Idea
Jul 3 '17 at 4:04
3
According to the official documentation you should try to avoid usingfindDOMNode. In most cases, you can attach a ref to the DOM node and avoid usingfindDOMNodeat all.
– Facyo Kouch
Jan 22 '18 at 20:11
Note that using this.refs by string mapping is deprecated, see: stackoverflow.com/questions/43873511/…
– Himmet Avsar
Jul 10 '18 at 13:25
Note: I had to usethis.myRef.current.scrollIntoView()instead ofwindow.scrollTo(0, this.myRef).
– Babbz77
Oct 24 '18 at 19:17
Yes, you are right. Have changed the answer.
– Roman Maksimov
Oct 27 '18 at 14:03
add a comment |
Using findDOMNode is going to be deprecated eventually.
The preferred method is to use callback refs.
github eslint
Please include the relevant part of the linked material so in case that gets removed your answer doesn't become useless.
– totymedli
Dec 10 '18 at 7:51
add a comment |
You can also use scrollIntoView method to scroll to a given element.
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
tesNode.scrollIntoView();
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
add a comment |
You could try this way:
handleScrollToElement = e => {
const elementTop = this.gate.offsetTop;
window.scrollTo(0, elementTop);
};
render(){
return(
<h2 ref={elem => (this.gate = elem)}>Payment gate</h2>
)}
Good solution, although you probably want e.offsetTop rather than this.gate.offsetTop and then pass this.gate to the function.
– KingOfHypocrites
Jul 30 '18 at 18:15
add a comment |
this worked for me
this.anyRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
where to put this
– su_sundariya
Oct 25 '18 at 7:19
in lifecycle method or constructor
– su_sundariya
Oct 25 '18 at 7:20
add a comment |
You can use something like componentDidUpdate
componentDidUpdate() {
var elem = testNode //your ref to the element say testNode in your case;
elem.scrollTop = elem.scrollHeight;
};
3
i think using element id is not preferred in react. It breaks the virtual dom concept
– iamsaksham
Mar 12 '18 at 3:31
Using the life cycle method is the way to go as far as WHEN/WHERE to run the code. But probably want to use the other methodologies you see in this answer for the actual code
– Dameo
Jul 20 '18 at 16:15
1
@iamsaksham updated with usingref
– Raviteja
Nov 9 '18 at 8:04
add a comment |
I might be late to the party but I was trying to implement dynamic refs to my project the proper way and all the answer I have found until know aren't quiet satisfying to my liking, so I came up with a solution that I think is simple and uses the native and recommended way of react to create the ref.
sometimes you find that the way documentation is wrote assumes that you have a known amount of views and in most cases this number is unknown so you need a way to solve the problem in this case, create dynamic refs to the unknown number of views you need to show in the class
so the most simple solution i could think of and worked flawlessly was to do as follows
class YourClass extends component {
state={
foo:"bar",
dynamicViews:,
myData: //get some data from the web
}
inputRef = React.createRef()
componentDidMount(){
this.createViews()
}
createViews = ()=>{
const trs=
for (let i = 1; i < this.state.myData.lenght; i++) {
let ref =`myrefRow ${i}`
this[ref]= React.createRef()
const row = (
<tr ref={this[ref]}>
<td>
`myRow ${i}`
</td>
</tr>
)
trs.push(row)
}
this.setState({dynamicViews:trs})
}
clickHandler = ()=>{
//const scrollToView = this.inputRef.current.value
//That to select the value of the inputbox bt for demostrate the //example
value=`myrefRow ${30}`
this[value].current.scrollIntoView({ behavior: "smooth", block: "start" });
}
render(){
return(
<div style={{display:"flex", flexDirection:"column"}}>
<Button onClick={this.clickHandler}> Search</Button>
<input ref={this.inputRef}/>
<table>
<tbody>
{this.state.dynamicViews}
<tbody>
<table>
</div>
)
}
}
export default YourClass
that way the scroll will go to whatever row you are looking for..
cheers and hope it helps others
add a comment |
What worked for me:
class MyComponent extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); // Create a ref
}
// Scroll to ref function
scrollToMyRef = () => {
window.scrollTo({
top:this.myRef.offsetTop,
// behavior: "smooth" // optional
});
};
// On component mount, scroll to ref
componentDidMount() {
this.scrollToMyRef();
}
// Render method. Note, that `div` element got `ref`.
render() {
return (
<div ref={this.myRef}>My component</div>
)
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43441856%2freactjs-how-to-scroll-to-an-element%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
Option 1: Use React.createRef (React 16.3 +)
class MyComponent extends Component {
constructor(props) {
super(props)
this.myRef = React.createRef() // Create a ref object
}
render() {
return <div ref={this.myRef}></div>
} // attach the ref property to a dom element
scrollToMyRef = () => window.scrollTo(0, this.myRef.current.offsetTop)
// run this method to execute scrolling.
}
Option 2: Use a ref callback
class MyComponent extends Component {
constructor(props){ // Optional, declare a class field to improve readability
super(props)
this.myRef=null
}
render() {
return <div ref={ (ref) => this.myRef=ref }></div>
} // Attach the dom element to a class field
scrollToMyRef = () => window.scrollTo(0, this.myRef.offsetTop)
// run this method to execute scrolling.
}
Don't use String refs.
String refs harm performance, aren't composable, and are on there way out (Aug 2018).
string refs have some issues, are considered legacy, and are likely to
be removed in one of the future releases. [Official React documentation]
resource1, resource2
Principles
- A ref can only be stored in a class component. (this will change in the future when the ref hook is released)
- In order to scroll to an element, the ref property in the class must be attached to an actual dom element; We are using the browser's native scrolling method, and we need to know the actual position of the element on the page.
- A ref (in either of the methods suggested above) can be passed on to a child as a prop.
Passing ref to a child
React.createRef - Pass the ref object as a prop to the child component.
render() {
return <ChildComp refProp={this.myRef}></ChildComp>
}
Then attach the ref prop to a dom element.
class ChildComp extends Component {
render () {
return <div ref={this.props.refProp} />
}
}
Update
In the past I recommended passing an options object to window.scrollTo. Edge and iOS don't support this form yet.
2
window.scrollTo(0, offsetTop)is a better option with better support among current browsers
– MoMo
Oct 2 '18 at 11:10
1
Could make sure you are consistent in your exemple. We're starting from myRef, going with domRef, and ending with tesNode ?. That is quite confusing
– Louis Lecocq
Oct 2 '18 at 12:42
1
@LouisLecocq, I value your feedback. I renamed variables for consistency. Thanks
– Ben Carp
Oct 2 '18 at 13:23
2
Obvious after the fact, but it is important to mention that this only works for native DOM elements and not just any React component.
– jpunk11
Nov 1 '18 at 19:19
2
@SimonFranzen Take a look at my updated answer - TLDR - class component case. When scrollToMyRef is called it will scroll to the child you attached the ref to. You can pass the method to a different child component, and trigger it from there.
– Ben Carp
Nov 8 '18 at 17:28
|
show 5 more comments
Option 1: Use React.createRef (React 16.3 +)
class MyComponent extends Component {
constructor(props) {
super(props)
this.myRef = React.createRef() // Create a ref object
}
render() {
return <div ref={this.myRef}></div>
} // attach the ref property to a dom element
scrollToMyRef = () => window.scrollTo(0, this.myRef.current.offsetTop)
// run this method to execute scrolling.
}
Option 2: Use a ref callback
class MyComponent extends Component {
constructor(props){ // Optional, declare a class field to improve readability
super(props)
this.myRef=null
}
render() {
return <div ref={ (ref) => this.myRef=ref }></div>
} // Attach the dom element to a class field
scrollToMyRef = () => window.scrollTo(0, this.myRef.offsetTop)
// run this method to execute scrolling.
}
Don't use String refs.
String refs harm performance, aren't composable, and are on there way out (Aug 2018).
string refs have some issues, are considered legacy, and are likely to
be removed in one of the future releases. [Official React documentation]
resource1, resource2
Principles
- A ref can only be stored in a class component. (this will change in the future when the ref hook is released)
- In order to scroll to an element, the ref property in the class must be attached to an actual dom element; We are using the browser's native scrolling method, and we need to know the actual position of the element on the page.
- A ref (in either of the methods suggested above) can be passed on to a child as a prop.
Passing ref to a child
React.createRef - Pass the ref object as a prop to the child component.
render() {
return <ChildComp refProp={this.myRef}></ChildComp>
}
Then attach the ref prop to a dom element.
class ChildComp extends Component {
render () {
return <div ref={this.props.refProp} />
}
}
Update
In the past I recommended passing an options object to window.scrollTo. Edge and iOS don't support this form yet.
2
window.scrollTo(0, offsetTop)is a better option with better support among current browsers
– MoMo
Oct 2 '18 at 11:10
1
Could make sure you are consistent in your exemple. We're starting from myRef, going with domRef, and ending with tesNode ?. That is quite confusing
– Louis Lecocq
Oct 2 '18 at 12:42
1
@LouisLecocq, I value your feedback. I renamed variables for consistency. Thanks
– Ben Carp
Oct 2 '18 at 13:23
2
Obvious after the fact, but it is important to mention that this only works for native DOM elements and not just any React component.
– jpunk11
Nov 1 '18 at 19:19
2
@SimonFranzen Take a look at my updated answer - TLDR - class component case. When scrollToMyRef is called it will scroll to the child you attached the ref to. You can pass the method to a different child component, and trigger it from there.
– Ben Carp
Nov 8 '18 at 17:28
|
show 5 more comments
Option 1: Use React.createRef (React 16.3 +)
class MyComponent extends Component {
constructor(props) {
super(props)
this.myRef = React.createRef() // Create a ref object
}
render() {
return <div ref={this.myRef}></div>
} // attach the ref property to a dom element
scrollToMyRef = () => window.scrollTo(0, this.myRef.current.offsetTop)
// run this method to execute scrolling.
}
Option 2: Use a ref callback
class MyComponent extends Component {
constructor(props){ // Optional, declare a class field to improve readability
super(props)
this.myRef=null
}
render() {
return <div ref={ (ref) => this.myRef=ref }></div>
} // Attach the dom element to a class field
scrollToMyRef = () => window.scrollTo(0, this.myRef.offsetTop)
// run this method to execute scrolling.
}
Don't use String refs.
String refs harm performance, aren't composable, and are on there way out (Aug 2018).
string refs have some issues, are considered legacy, and are likely to
be removed in one of the future releases. [Official React documentation]
resource1, resource2
Principles
- A ref can only be stored in a class component. (this will change in the future when the ref hook is released)
- In order to scroll to an element, the ref property in the class must be attached to an actual dom element; We are using the browser's native scrolling method, and we need to know the actual position of the element on the page.
- A ref (in either of the methods suggested above) can be passed on to a child as a prop.
Passing ref to a child
React.createRef - Pass the ref object as a prop to the child component.
render() {
return <ChildComp refProp={this.myRef}></ChildComp>
}
Then attach the ref prop to a dom element.
class ChildComp extends Component {
render () {
return <div ref={this.props.refProp} />
}
}
Update
In the past I recommended passing an options object to window.scrollTo. Edge and iOS don't support this form yet.
Option 1: Use React.createRef (React 16.3 +)
class MyComponent extends Component {
constructor(props) {
super(props)
this.myRef = React.createRef() // Create a ref object
}
render() {
return <div ref={this.myRef}></div>
} // attach the ref property to a dom element
scrollToMyRef = () => window.scrollTo(0, this.myRef.current.offsetTop)
// run this method to execute scrolling.
}
Option 2: Use a ref callback
class MyComponent extends Component {
constructor(props){ // Optional, declare a class field to improve readability
super(props)
this.myRef=null
}
render() {
return <div ref={ (ref) => this.myRef=ref }></div>
} // Attach the dom element to a class field
scrollToMyRef = () => window.scrollTo(0, this.myRef.offsetTop)
// run this method to execute scrolling.
}
Don't use String refs.
String refs harm performance, aren't composable, and are on there way out (Aug 2018).
string refs have some issues, are considered legacy, and are likely to
be removed in one of the future releases. [Official React documentation]
resource1, resource2
Principles
- A ref can only be stored in a class component. (this will change in the future when the ref hook is released)
- In order to scroll to an element, the ref property in the class must be attached to an actual dom element; We are using the browser's native scrolling method, and we need to know the actual position of the element on the page.
- A ref (in either of the methods suggested above) can be passed on to a child as a prop.
Passing ref to a child
React.createRef - Pass the ref object as a prop to the child component.
render() {
return <ChildComp refProp={this.myRef}></ChildComp>
}
Then attach the ref prop to a dom element.
class ChildComp extends Component {
render () {
return <div ref={this.props.refProp} />
}
}
Update
In the past I recommended passing an options object to window.scrollTo. Edge and iOS don't support this form yet.
edited Jan 31 at 14:25
Amirhossein Mehrvarzi
7,34542952
7,34542952
answered Aug 13 '18 at 19:03
Ben CarpBen Carp
1,192822
1,192822
2
window.scrollTo(0, offsetTop)is a better option with better support among current browsers
– MoMo
Oct 2 '18 at 11:10
1
Could make sure you are consistent in your exemple. We're starting from myRef, going with domRef, and ending with tesNode ?. That is quite confusing
– Louis Lecocq
Oct 2 '18 at 12:42
1
@LouisLecocq, I value your feedback. I renamed variables for consistency. Thanks
– Ben Carp
Oct 2 '18 at 13:23
2
Obvious after the fact, but it is important to mention that this only works for native DOM elements and not just any React component.
– jpunk11
Nov 1 '18 at 19:19
2
@SimonFranzen Take a look at my updated answer - TLDR - class component case. When scrollToMyRef is called it will scroll to the child you attached the ref to. You can pass the method to a different child component, and trigger it from there.
– Ben Carp
Nov 8 '18 at 17:28
|
show 5 more comments
2
window.scrollTo(0, offsetTop)is a better option with better support among current browsers
– MoMo
Oct 2 '18 at 11:10
1
Could make sure you are consistent in your exemple. We're starting from myRef, going with domRef, and ending with tesNode ?. That is quite confusing
– Louis Lecocq
Oct 2 '18 at 12:42
1
@LouisLecocq, I value your feedback. I renamed variables for consistency. Thanks
– Ben Carp
Oct 2 '18 at 13:23
2
Obvious after the fact, but it is important to mention that this only works for native DOM elements and not just any React component.
– jpunk11
Nov 1 '18 at 19:19
2
@SimonFranzen Take a look at my updated answer - TLDR - class component case. When scrollToMyRef is called it will scroll to the child you attached the ref to. You can pass the method to a different child component, and trigger it from there.
– Ben Carp
Nov 8 '18 at 17:28
2
2
window.scrollTo(0, offsetTop) is a better option with better support among current browsers– MoMo
Oct 2 '18 at 11:10
window.scrollTo(0, offsetTop) is a better option with better support among current browsers– MoMo
Oct 2 '18 at 11:10
1
1
Could make sure you are consistent in your exemple. We're starting from myRef, going with domRef, and ending with tesNode ?. That is quite confusing
– Louis Lecocq
Oct 2 '18 at 12:42
Could make sure you are consistent in your exemple. We're starting from myRef, going with domRef, and ending with tesNode ?. That is quite confusing
– Louis Lecocq
Oct 2 '18 at 12:42
1
1
@LouisLecocq, I value your feedback. I renamed variables for consistency. Thanks
– Ben Carp
Oct 2 '18 at 13:23
@LouisLecocq, I value your feedback. I renamed variables for consistency. Thanks
– Ben Carp
Oct 2 '18 at 13:23
2
2
Obvious after the fact, but it is important to mention that this only works for native DOM elements and not just any React component.
– jpunk11
Nov 1 '18 at 19:19
Obvious after the fact, but it is important to mention that this only works for native DOM elements and not just any React component.
– jpunk11
Nov 1 '18 at 19:19
2
2
@SimonFranzen Take a look at my updated answer - TLDR - class component case. When scrollToMyRef is called it will scroll to the child you attached the ref to. You can pass the method to a different child component, and trigger it from there.
– Ben Carp
Nov 8 '18 at 17:28
@SimonFranzen Take a look at my updated answer - TLDR - class component case. When scrollToMyRef is called it will scroll to the child you attached the ref to. You can pass the method to a different child component, and trigger it from there.
– Ben Carp
Nov 8 '18 at 17:28
|
show 5 more comments
Just find the top position of the element you've already determined https://www.w3schools.com/Jsref/prop_element_offsettop.asp then scroll to this position via scrollTo method https://www.w3schools.com/Jsref/met_win_scrollto.asp
Something like this should work:
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
window.scrollTo(0, tesNode.offsetTop);
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
UPDATE:
since React v16.3 the React.createRef() is preferred
constructor(props) {
super(props);
this.myRef = React.createRef();
}
handleScrollToElement(event) {
if (<some_logic>){
window.scrollTo(0, this.myRef.current.offsetTop);
}
}
render() {
return (
<div>
<div ref={this.myRef}></div>
</div>)
}
1
This is the better answer. UsingReactDOM.findDomNode()is better practice - since React re-renders components, a div that you simply get by its ID might not exist by the time you call the function
– Good Idea
Jul 3 '17 at 4:04
3
According to the official documentation you should try to avoid usingfindDOMNode. In most cases, you can attach a ref to the DOM node and avoid usingfindDOMNodeat all.
– Facyo Kouch
Jan 22 '18 at 20:11
Note that using this.refs by string mapping is deprecated, see: stackoverflow.com/questions/43873511/…
– Himmet Avsar
Jul 10 '18 at 13:25
Note: I had to usethis.myRef.current.scrollIntoView()instead ofwindow.scrollTo(0, this.myRef).
– Babbz77
Oct 24 '18 at 19:17
Yes, you are right. Have changed the answer.
– Roman Maksimov
Oct 27 '18 at 14:03
add a comment |
Just find the top position of the element you've already determined https://www.w3schools.com/Jsref/prop_element_offsettop.asp then scroll to this position via scrollTo method https://www.w3schools.com/Jsref/met_win_scrollto.asp
Something like this should work:
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
window.scrollTo(0, tesNode.offsetTop);
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
UPDATE:
since React v16.3 the React.createRef() is preferred
constructor(props) {
super(props);
this.myRef = React.createRef();
}
handleScrollToElement(event) {
if (<some_logic>){
window.scrollTo(0, this.myRef.current.offsetTop);
}
}
render() {
return (
<div>
<div ref={this.myRef}></div>
</div>)
}
1
This is the better answer. UsingReactDOM.findDomNode()is better practice - since React re-renders components, a div that you simply get by its ID might not exist by the time you call the function
– Good Idea
Jul 3 '17 at 4:04
3
According to the official documentation you should try to avoid usingfindDOMNode. In most cases, you can attach a ref to the DOM node and avoid usingfindDOMNodeat all.
– Facyo Kouch
Jan 22 '18 at 20:11
Note that using this.refs by string mapping is deprecated, see: stackoverflow.com/questions/43873511/…
– Himmet Avsar
Jul 10 '18 at 13:25
Note: I had to usethis.myRef.current.scrollIntoView()instead ofwindow.scrollTo(0, this.myRef).
– Babbz77
Oct 24 '18 at 19:17
Yes, you are right. Have changed the answer.
– Roman Maksimov
Oct 27 '18 at 14:03
add a comment |
Just find the top position of the element you've already determined https://www.w3schools.com/Jsref/prop_element_offsettop.asp then scroll to this position via scrollTo method https://www.w3schools.com/Jsref/met_win_scrollto.asp
Something like this should work:
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
window.scrollTo(0, tesNode.offsetTop);
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
UPDATE:
since React v16.3 the React.createRef() is preferred
constructor(props) {
super(props);
this.myRef = React.createRef();
}
handleScrollToElement(event) {
if (<some_logic>){
window.scrollTo(0, this.myRef.current.offsetTop);
}
}
render() {
return (
<div>
<div ref={this.myRef}></div>
</div>)
}
Just find the top position of the element you've already determined https://www.w3schools.com/Jsref/prop_element_offsettop.asp then scroll to this position via scrollTo method https://www.w3schools.com/Jsref/met_win_scrollto.asp
Something like this should work:
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
window.scrollTo(0, tesNode.offsetTop);
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
UPDATE:
since React v16.3 the React.createRef() is preferred
constructor(props) {
super(props);
this.myRef = React.createRef();
}
handleScrollToElement(event) {
if (<some_logic>){
window.scrollTo(0, this.myRef.current.offsetTop);
}
}
render() {
return (
<div>
<div ref={this.myRef}></div>
</div>)
}
edited Oct 27 '18 at 14:02
answered Apr 16 '17 at 22:29
Roman MaksimovRoman Maksimov
1,0511413
1,0511413
1
This is the better answer. UsingReactDOM.findDomNode()is better practice - since React re-renders components, a div that you simply get by its ID might not exist by the time you call the function
– Good Idea
Jul 3 '17 at 4:04
3
According to the official documentation you should try to avoid usingfindDOMNode. In most cases, you can attach a ref to the DOM node and avoid usingfindDOMNodeat all.
– Facyo Kouch
Jan 22 '18 at 20:11
Note that using this.refs by string mapping is deprecated, see: stackoverflow.com/questions/43873511/…
– Himmet Avsar
Jul 10 '18 at 13:25
Note: I had to usethis.myRef.current.scrollIntoView()instead ofwindow.scrollTo(0, this.myRef).
– Babbz77
Oct 24 '18 at 19:17
Yes, you are right. Have changed the answer.
– Roman Maksimov
Oct 27 '18 at 14:03
add a comment |
1
This is the better answer. UsingReactDOM.findDomNode()is better practice - since React re-renders components, a div that you simply get by its ID might not exist by the time you call the function
– Good Idea
Jul 3 '17 at 4:04
3
According to the official documentation you should try to avoid usingfindDOMNode. In most cases, you can attach a ref to the DOM node and avoid usingfindDOMNodeat all.
– Facyo Kouch
Jan 22 '18 at 20:11
Note that using this.refs by string mapping is deprecated, see: stackoverflow.com/questions/43873511/…
– Himmet Avsar
Jul 10 '18 at 13:25
Note: I had to usethis.myRef.current.scrollIntoView()instead ofwindow.scrollTo(0, this.myRef).
– Babbz77
Oct 24 '18 at 19:17
Yes, you are right. Have changed the answer.
– Roman Maksimov
Oct 27 '18 at 14:03
1
1
This is the better answer. Using
ReactDOM.findDomNode() is better practice - since React re-renders components, a div that you simply get by its ID might not exist by the time you call the function– Good Idea
Jul 3 '17 at 4:04
This is the better answer. Using
ReactDOM.findDomNode() is better practice - since React re-renders components, a div that you simply get by its ID might not exist by the time you call the function– Good Idea
Jul 3 '17 at 4:04
3
3
According to the official documentation you should try to avoid using
findDOMNode. In most cases, you can attach a ref to the DOM node and avoid using findDOMNode at all.– Facyo Kouch
Jan 22 '18 at 20:11
According to the official documentation you should try to avoid using
findDOMNode. In most cases, you can attach a ref to the DOM node and avoid using findDOMNode at all.– Facyo Kouch
Jan 22 '18 at 20:11
Note that using this.refs by string mapping is deprecated, see: stackoverflow.com/questions/43873511/…
– Himmet Avsar
Jul 10 '18 at 13:25
Note that using this.refs by string mapping is deprecated, see: stackoverflow.com/questions/43873511/…
– Himmet Avsar
Jul 10 '18 at 13:25
Note: I had to use
this.myRef.current.scrollIntoView() instead of window.scrollTo(0, this.myRef).– Babbz77
Oct 24 '18 at 19:17
Note: I had to use
this.myRef.current.scrollIntoView() instead of window.scrollTo(0, this.myRef).– Babbz77
Oct 24 '18 at 19:17
Yes, you are right. Have changed the answer.
– Roman Maksimov
Oct 27 '18 at 14:03
Yes, you are right. Have changed the answer.
– Roman Maksimov
Oct 27 '18 at 14:03
add a comment |
Using findDOMNode is going to be deprecated eventually.
The preferred method is to use callback refs.
github eslint
Please include the relevant part of the linked material so in case that gets removed your answer doesn't become useless.
– totymedli
Dec 10 '18 at 7:51
add a comment |
Using findDOMNode is going to be deprecated eventually.
The preferred method is to use callback refs.
github eslint
Please include the relevant part of the linked material so in case that gets removed your answer doesn't become useless.
– totymedli
Dec 10 '18 at 7:51
add a comment |
Using findDOMNode is going to be deprecated eventually.
The preferred method is to use callback refs.
github eslint
Using findDOMNode is going to be deprecated eventually.
The preferred method is to use callback refs.
github eslint
edited Jan 11 at 7:43
Afaq
337311
337311
answered Jan 2 '18 at 17:45
sww314sww314
662611
662611
Please include the relevant part of the linked material so in case that gets removed your answer doesn't become useless.
– totymedli
Dec 10 '18 at 7:51
add a comment |
Please include the relevant part of the linked material so in case that gets removed your answer doesn't become useless.
– totymedli
Dec 10 '18 at 7:51
Please include the relevant part of the linked material so in case that gets removed your answer doesn't become useless.
– totymedli
Dec 10 '18 at 7:51
Please include the relevant part of the linked material so in case that gets removed your answer doesn't become useless.
– totymedli
Dec 10 '18 at 7:51
add a comment |
You can also use scrollIntoView method to scroll to a given element.
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
tesNode.scrollIntoView();
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
add a comment |
You can also use scrollIntoView method to scroll to a given element.
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
tesNode.scrollIntoView();
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
add a comment |
You can also use scrollIntoView method to scroll to a given element.
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
tesNode.scrollIntoView();
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
You can also use scrollIntoView method to scroll to a given element.
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
tesNode.scrollIntoView();
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
answered Apr 23 '18 at 12:45
Farshad JFarshad J
8115
8115
add a comment |
add a comment |
You could try this way:
handleScrollToElement = e => {
const elementTop = this.gate.offsetTop;
window.scrollTo(0, elementTop);
};
render(){
return(
<h2 ref={elem => (this.gate = elem)}>Payment gate</h2>
)}
Good solution, although you probably want e.offsetTop rather than this.gate.offsetTop and then pass this.gate to the function.
– KingOfHypocrites
Jul 30 '18 at 18:15
add a comment |
You could try this way:
handleScrollToElement = e => {
const elementTop = this.gate.offsetTop;
window.scrollTo(0, elementTop);
};
render(){
return(
<h2 ref={elem => (this.gate = elem)}>Payment gate</h2>
)}
Good solution, although you probably want e.offsetTop rather than this.gate.offsetTop and then pass this.gate to the function.
– KingOfHypocrites
Jul 30 '18 at 18:15
add a comment |
You could try this way:
handleScrollToElement = e => {
const elementTop = this.gate.offsetTop;
window.scrollTo(0, elementTop);
};
render(){
return(
<h2 ref={elem => (this.gate = elem)}>Payment gate</h2>
)}
You could try this way:
handleScrollToElement = e => {
const elementTop = this.gate.offsetTop;
window.scrollTo(0, elementTop);
};
render(){
return(
<h2 ref={elem => (this.gate = elem)}>Payment gate</h2>
)}
edited Apr 17 '18 at 10:16
p-a-o-l-o
6,0662930
6,0662930
answered Apr 17 '18 at 8:22
jirina Brezinovajirina Brezinova
6112
6112
Good solution, although you probably want e.offsetTop rather than this.gate.offsetTop and then pass this.gate to the function.
– KingOfHypocrites
Jul 30 '18 at 18:15
add a comment |
Good solution, although you probably want e.offsetTop rather than this.gate.offsetTop and then pass this.gate to the function.
– KingOfHypocrites
Jul 30 '18 at 18:15
Good solution, although you probably want e.offsetTop rather than this.gate.offsetTop and then pass this.gate to the function.
– KingOfHypocrites
Jul 30 '18 at 18:15
Good solution, although you probably want e.offsetTop rather than this.gate.offsetTop and then pass this.gate to the function.
– KingOfHypocrites
Jul 30 '18 at 18:15
add a comment |
this worked for me
this.anyRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
where to put this
– su_sundariya
Oct 25 '18 at 7:19
in lifecycle method or constructor
– su_sundariya
Oct 25 '18 at 7:20
add a comment |
this worked for me
this.anyRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
where to put this
– su_sundariya
Oct 25 '18 at 7:19
in lifecycle method or constructor
– su_sundariya
Oct 25 '18 at 7:20
add a comment |
this worked for me
this.anyRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
this worked for me
this.anyRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
answered Sep 27 '18 at 2:41
chiichii
327114
327114
where to put this
– su_sundariya
Oct 25 '18 at 7:19
in lifecycle method or constructor
– su_sundariya
Oct 25 '18 at 7:20
add a comment |
where to put this
– su_sundariya
Oct 25 '18 at 7:19
in lifecycle method or constructor
– su_sundariya
Oct 25 '18 at 7:20
where to put this
– su_sundariya
Oct 25 '18 at 7:19
where to put this
– su_sundariya
Oct 25 '18 at 7:19
in lifecycle method or constructor
– su_sundariya
Oct 25 '18 at 7:20
in lifecycle method or constructor
– su_sundariya
Oct 25 '18 at 7:20
add a comment |
You can use something like componentDidUpdate
componentDidUpdate() {
var elem = testNode //your ref to the element say testNode in your case;
elem.scrollTop = elem.scrollHeight;
};
3
i think using element id is not preferred in react. It breaks the virtual dom concept
– iamsaksham
Mar 12 '18 at 3:31
Using the life cycle method is the way to go as far as WHEN/WHERE to run the code. But probably want to use the other methodologies you see in this answer for the actual code
– Dameo
Jul 20 '18 at 16:15
1
@iamsaksham updated with usingref
– Raviteja
Nov 9 '18 at 8:04
add a comment |
You can use something like componentDidUpdate
componentDidUpdate() {
var elem = testNode //your ref to the element say testNode in your case;
elem.scrollTop = elem.scrollHeight;
};
3
i think using element id is not preferred in react. It breaks the virtual dom concept
– iamsaksham
Mar 12 '18 at 3:31
Using the life cycle method is the way to go as far as WHEN/WHERE to run the code. But probably want to use the other methodologies you see in this answer for the actual code
– Dameo
Jul 20 '18 at 16:15
1
@iamsaksham updated with usingref
– Raviteja
Nov 9 '18 at 8:04
add a comment |
You can use something like componentDidUpdate
componentDidUpdate() {
var elem = testNode //your ref to the element say testNode in your case;
elem.scrollTop = elem.scrollHeight;
};
You can use something like componentDidUpdate
componentDidUpdate() {
var elem = testNode //your ref to the element say testNode in your case;
elem.scrollTop = elem.scrollHeight;
};
edited Nov 9 '18 at 8:04
answered Apr 17 '17 at 9:33
RavitejaRaviteja
2,22182443
2,22182443
3
i think using element id is not preferred in react. It breaks the virtual dom concept
– iamsaksham
Mar 12 '18 at 3:31
Using the life cycle method is the way to go as far as WHEN/WHERE to run the code. But probably want to use the other methodologies you see in this answer for the actual code
– Dameo
Jul 20 '18 at 16:15
1
@iamsaksham updated with usingref
– Raviteja
Nov 9 '18 at 8:04
add a comment |
3
i think using element id is not preferred in react. It breaks the virtual dom concept
– iamsaksham
Mar 12 '18 at 3:31
Using the life cycle method is the way to go as far as WHEN/WHERE to run the code. But probably want to use the other methodologies you see in this answer for the actual code
– Dameo
Jul 20 '18 at 16:15
1
@iamsaksham updated with usingref
– Raviteja
Nov 9 '18 at 8:04
3
3
i think using element id is not preferred in react. It breaks the virtual dom concept
– iamsaksham
Mar 12 '18 at 3:31
i think using element id is not preferred in react. It breaks the virtual dom concept
– iamsaksham
Mar 12 '18 at 3:31
Using the life cycle method is the way to go as far as WHEN/WHERE to run the code. But probably want to use the other methodologies you see in this answer for the actual code
– Dameo
Jul 20 '18 at 16:15
Using the life cycle method is the way to go as far as WHEN/WHERE to run the code. But probably want to use the other methodologies you see in this answer for the actual code
– Dameo
Jul 20 '18 at 16:15
1
1
@iamsaksham updated with using
ref– Raviteja
Nov 9 '18 at 8:04
@iamsaksham updated with using
ref– Raviteja
Nov 9 '18 at 8:04
add a comment |
I might be late to the party but I was trying to implement dynamic refs to my project the proper way and all the answer I have found until know aren't quiet satisfying to my liking, so I came up with a solution that I think is simple and uses the native and recommended way of react to create the ref.
sometimes you find that the way documentation is wrote assumes that you have a known amount of views and in most cases this number is unknown so you need a way to solve the problem in this case, create dynamic refs to the unknown number of views you need to show in the class
so the most simple solution i could think of and worked flawlessly was to do as follows
class YourClass extends component {
state={
foo:"bar",
dynamicViews:,
myData: //get some data from the web
}
inputRef = React.createRef()
componentDidMount(){
this.createViews()
}
createViews = ()=>{
const trs=
for (let i = 1; i < this.state.myData.lenght; i++) {
let ref =`myrefRow ${i}`
this[ref]= React.createRef()
const row = (
<tr ref={this[ref]}>
<td>
`myRow ${i}`
</td>
</tr>
)
trs.push(row)
}
this.setState({dynamicViews:trs})
}
clickHandler = ()=>{
//const scrollToView = this.inputRef.current.value
//That to select the value of the inputbox bt for demostrate the //example
value=`myrefRow ${30}`
this[value].current.scrollIntoView({ behavior: "smooth", block: "start" });
}
render(){
return(
<div style={{display:"flex", flexDirection:"column"}}>
<Button onClick={this.clickHandler}> Search</Button>
<input ref={this.inputRef}/>
<table>
<tbody>
{this.state.dynamicViews}
<tbody>
<table>
</div>
)
}
}
export default YourClass
that way the scroll will go to whatever row you are looking for..
cheers and hope it helps others
add a comment |
I might be late to the party but I was trying to implement dynamic refs to my project the proper way and all the answer I have found until know aren't quiet satisfying to my liking, so I came up with a solution that I think is simple and uses the native and recommended way of react to create the ref.
sometimes you find that the way documentation is wrote assumes that you have a known amount of views and in most cases this number is unknown so you need a way to solve the problem in this case, create dynamic refs to the unknown number of views you need to show in the class
so the most simple solution i could think of and worked flawlessly was to do as follows
class YourClass extends component {
state={
foo:"bar",
dynamicViews:,
myData: //get some data from the web
}
inputRef = React.createRef()
componentDidMount(){
this.createViews()
}
createViews = ()=>{
const trs=
for (let i = 1; i < this.state.myData.lenght; i++) {
let ref =`myrefRow ${i}`
this[ref]= React.createRef()
const row = (
<tr ref={this[ref]}>
<td>
`myRow ${i}`
</td>
</tr>
)
trs.push(row)
}
this.setState({dynamicViews:trs})
}
clickHandler = ()=>{
//const scrollToView = this.inputRef.current.value
//That to select the value of the inputbox bt for demostrate the //example
value=`myrefRow ${30}`
this[value].current.scrollIntoView({ behavior: "smooth", block: "start" });
}
render(){
return(
<div style={{display:"flex", flexDirection:"column"}}>
<Button onClick={this.clickHandler}> Search</Button>
<input ref={this.inputRef}/>
<table>
<tbody>
{this.state.dynamicViews}
<tbody>
<table>
</div>
)
}
}
export default YourClass
that way the scroll will go to whatever row you are looking for..
cheers and hope it helps others
add a comment |
I might be late to the party but I was trying to implement dynamic refs to my project the proper way and all the answer I have found until know aren't quiet satisfying to my liking, so I came up with a solution that I think is simple and uses the native and recommended way of react to create the ref.
sometimes you find that the way documentation is wrote assumes that you have a known amount of views and in most cases this number is unknown so you need a way to solve the problem in this case, create dynamic refs to the unknown number of views you need to show in the class
so the most simple solution i could think of and worked flawlessly was to do as follows
class YourClass extends component {
state={
foo:"bar",
dynamicViews:,
myData: //get some data from the web
}
inputRef = React.createRef()
componentDidMount(){
this.createViews()
}
createViews = ()=>{
const trs=
for (let i = 1; i < this.state.myData.lenght; i++) {
let ref =`myrefRow ${i}`
this[ref]= React.createRef()
const row = (
<tr ref={this[ref]}>
<td>
`myRow ${i}`
</td>
</tr>
)
trs.push(row)
}
this.setState({dynamicViews:trs})
}
clickHandler = ()=>{
//const scrollToView = this.inputRef.current.value
//That to select the value of the inputbox bt for demostrate the //example
value=`myrefRow ${30}`
this[value].current.scrollIntoView({ behavior: "smooth", block: "start" });
}
render(){
return(
<div style={{display:"flex", flexDirection:"column"}}>
<Button onClick={this.clickHandler}> Search</Button>
<input ref={this.inputRef}/>
<table>
<tbody>
{this.state.dynamicViews}
<tbody>
<table>
</div>
)
}
}
export default YourClass
that way the scroll will go to whatever row you are looking for..
cheers and hope it helps others
I might be late to the party but I was trying to implement dynamic refs to my project the proper way and all the answer I have found until know aren't quiet satisfying to my liking, so I came up with a solution that I think is simple and uses the native and recommended way of react to create the ref.
sometimes you find that the way documentation is wrote assumes that you have a known amount of views and in most cases this number is unknown so you need a way to solve the problem in this case, create dynamic refs to the unknown number of views you need to show in the class
so the most simple solution i could think of and worked flawlessly was to do as follows
class YourClass extends component {
state={
foo:"bar",
dynamicViews:,
myData: //get some data from the web
}
inputRef = React.createRef()
componentDidMount(){
this.createViews()
}
createViews = ()=>{
const trs=
for (let i = 1; i < this.state.myData.lenght; i++) {
let ref =`myrefRow ${i}`
this[ref]= React.createRef()
const row = (
<tr ref={this[ref]}>
<td>
`myRow ${i}`
</td>
</tr>
)
trs.push(row)
}
this.setState({dynamicViews:trs})
}
clickHandler = ()=>{
//const scrollToView = this.inputRef.current.value
//That to select the value of the inputbox bt for demostrate the //example
value=`myrefRow ${30}`
this[value].current.scrollIntoView({ behavior: "smooth", block: "start" });
}
render(){
return(
<div style={{display:"flex", flexDirection:"column"}}>
<Button onClick={this.clickHandler}> Search</Button>
<input ref={this.inputRef}/>
<table>
<tbody>
{this.state.dynamicViews}
<tbody>
<table>
</div>
)
}
}
export default YourClass
that way the scroll will go to whatever row you are looking for..
cheers and hope it helps others
edited Jan 11 at 7:44
Afaq
337311
337311
answered Nov 4 '18 at 18:07
Miguel SedekMiguel Sedek
5817
5817
add a comment |
add a comment |
What worked for me:
class MyComponent extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); // Create a ref
}
// Scroll to ref function
scrollToMyRef = () => {
window.scrollTo({
top:this.myRef.offsetTop,
// behavior: "smooth" // optional
});
};
// On component mount, scroll to ref
componentDidMount() {
this.scrollToMyRef();
}
// Render method. Note, that `div` element got `ref`.
render() {
return (
<div ref={this.myRef}>My component</div>
)
}
}
add a comment |
What worked for me:
class MyComponent extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); // Create a ref
}
// Scroll to ref function
scrollToMyRef = () => {
window.scrollTo({
top:this.myRef.offsetTop,
// behavior: "smooth" // optional
});
};
// On component mount, scroll to ref
componentDidMount() {
this.scrollToMyRef();
}
// Render method. Note, that `div` element got `ref`.
render() {
return (
<div ref={this.myRef}>My component</div>
)
}
}
add a comment |
What worked for me:
class MyComponent extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); // Create a ref
}
// Scroll to ref function
scrollToMyRef = () => {
window.scrollTo({
top:this.myRef.offsetTop,
// behavior: "smooth" // optional
});
};
// On component mount, scroll to ref
componentDidMount() {
this.scrollToMyRef();
}
// Render method. Note, that `div` element got `ref`.
render() {
return (
<div ref={this.myRef}>My component</div>
)
}
}
What worked for me:
class MyComponent extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); // Create a ref
}
// Scroll to ref function
scrollToMyRef = () => {
window.scrollTo({
top:this.myRef.offsetTop,
// behavior: "smooth" // optional
});
};
// On component mount, scroll to ref
componentDidMount() {
this.scrollToMyRef();
}
// Render method. Note, that `div` element got `ref`.
render() {
return (
<div ref={this.myRef}>My component</div>
)
}
}
edited Dec 20 '18 at 9:18
answered Dec 18 '18 at 8:41
Artur BarseghyanArtur Barseghyan
4,84222627
4,84222627
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43441856%2freactjs-how-to-scroll-to-an-element%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
For a bundled solution: npmjs.com/package/react-scroll-to-component
– tokland
Dec 21 '17 at 11:00