repl.it
@abouthalf/

reforward

React

experimenting with forwarded refs

fork
loading
Files
  • src
    • App.js
    • App.css
    • App.test.js
    • index.css
    • index.js
    • logo.svg
  • public
  • Packager files
  • package.json
src/App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import React, { Component } from 'react';

import './App.css';

const rando = (min, max) => {
  return Math.floor(Math.random()*(max-min+1)+min);
}

class App extends Component {

  constructor(props) {
    super(props);
    this.view = React.createRef();
    this.current = rando(1, 100);
    console.log(this.current);
  }

  state = {
    posts: []
  }

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then(res => {
        if (res.ok) {
          return res.json()
        }
        return []
      })
      .then(posts => {
        this.setState({ posts })
      })
      .then(() => {
        if (this.view.current) {
          this.view.current.scrollIntoView({behavior: "smooth"});
        }
      })
  }

  render() {
    const { posts } = this.state;
    return (
      <div className="App">
        <ul>
          {posts.map((post, i) => {
            const { id, title, body } = post;
            let index = i + 1;
            if (index === this.current) {
              console.log("current");
              return <RefPost ref={this.view} id={id} title={title} body={body} key={i} />
            }
            return <Post id={id} title={title} body={body} key={i} />
          })}
        </ul>
      </div>
    );
  }
}

export default App;

class Post extends Component {
  render() {
    const { id, title, body } = this.props;
    return (<li>
      <h3>{id}: {title}</h3>
      <p>{body}</p>
    </li>)
  }
}

const RefPost = React.forwardRef(( props, ref ) => {
  const { title, body } = props;
  return <li ref={ref}>
      <h3>{title}</h3>
      <p>{body}</p>
    </li>
})