Muhaimin
Muhaimin

Reputation: 1643

Single refs used by many elements

I know this is not common case but is it possible to have case like this

render () {
   return (
      <div>
          blablabalblbla balbal <span ref={ el => this.title = el }></span>'s adsdasd
          <p>would sjdfdfjhdsjfjdf <span ref={ el => this.title = el }></span>?</span></p>
      </div>
   }
}

and later using componentDidMount() I set it like this

this.title.innerHTML = obj.title

now only the last element will affected. Is there any technique make it work for both elements?

Upvotes: 0

Views: 56

Answers (1)

Fabian Schultz
Fabian Schultz

Reputation: 18556

You're thinking too complicated. First off, the general consensus is to try and not use refs wherever possible. They're not really following the principles and concepts of React, as is setting the innerHTML. With React, you should try to not modify/read the DOM directly. Second, what you're describing can be solved with React's state. Take a look at this example:

class Example extends React.Component {
  constructor() {
    super();
    this.state = { title: 'Hello' };
    this.onChange = this.onChange.bind(this);
  }
  onChange(e) { this.setState({ title: e.target.value }); }
  render() {
    return(
      <div>
        blablabalblbla balbal {this.state.title}'s adsdasd
        <p>would sjdfdfjhdsjfjdf {this.state.title}?</p>
        <input onChange={this.onChange} value={this.state.title} />
      </div>
    );
  }
}

ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>

You can use a state element inside your JSX like a variable and change it in your code with this.setState(). React will then automatically update your component's "HTML" in the DOM.

Upvotes: 1

Related Questions