Ghan Ghan - 1 month ago 20
Javascript Question

React: Get target's DOM children

Let's say you have an HTML unordered list, and you'd like to create a React element from it:

<ul id="mylist">
<li><a href="">Something</a></li>
<li><a href="">Another thing</a></li>
<li><a href="">Third thing</a></li>
</ul>


then in JS:

ReactDOM.render(<MyNewList />, document.getElementById('mylist'));


I'd like to retrieve the original HTML LIs and use them in my MyNewList component. Something like:

class MyNewList extends React.Component {
componentWillMount() {
let listArray = this.props.whatever
}
...
}


Is that possible? How?

thanks.

Answer

Here is how you can achieve this: http://codepen.io/PiotrBerebecki/pen/BLbjEJ

It's a rough structure, so you would have to refactor it a bit so that it fits your desired use.

HTML:

<body>

  <ul id="mylist">
    <li><a href="">Something</a></li>
    <li><a href="">Another thing</a></li>
    <li><a href="">Third thing</a></li>
  </ul>

</body>

JS:

class MyNewList  extends React.Component {
  constructor() {
    super();
    this.state = {
      myList: null
    };
  }

  componentWillMount() {
    const myList = document.getElementById('mylist').children;
    this.setState({
      myList: myList
    });
  }

  render() {
    let renderList = 'Loading...'

    if (this.state.myList) {
      renderList = Array.prototype.map.call(this.state.myList, function(item) {
        return (
          <li>{item.textContent} found in HTML</li>
        );
      });
    }

    return (
      <ul id="myNewlist">
        {renderList}
      </ul>
    );
  }
}

ReactDOM.render(
  <MyNewList />,
  document.getElementById('mylist')
);