Is it possible to use `ref` for a TextNode?

Viewed 601

This:

import React from "react";
import { render } from "react-dom";

let $container;

render(
  <b ref={e => ($container = e)}>
    {"one"}two{"six"}
  </b>,
  document.getElementById("root")
);

console.log($container);

will get me the <b> element:

<b>
  <!-- react-text: 2 -->
  "one"
  <!-- /react-text -->
  <!-- react-text: 3 -->
  "two"
  <!-- /react-text -->
  <!-- react-text: 4 -->
  "six"
  <!-- /react-text -->
</b>

But, what if I want a reference to one of the TextNodes?
Is there a public api for this? Maybe a special type for TextNodes so I can pass props to createElement?

2 Answers

Here's what I did: I created a component that solely consists of a text and referenced its TextNode in the DOM with ReactDOM.findDOMNode like so:

class TextNode extends React.Component {

  componentDidMount() {
      this.textNode = ReactDOM.findDOMNode(this); // Will be the DOM text node
  }

  render() {
    return this.props.text;
  }

}

In your example I could do something like this:

render(
  <b>
    <TextNode text={"one"} />
    <TextNode text="two" />
    <TextNode text={"six"} />
  </b>,
  document.getElementById("root")
);

The resulting HTML would not have any spans:

<b>onetwosix</b>

while the DOM would have a <b> element with 3 text nodes inside.

Related