ref element

access more than one element using createRef

by zafarn8

HTML

<div id="app"></div>

React

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    // this.myRef = React.createRef();
    this.textInput = null;

    this.state = {
      fname:""
    }
  }

  setTextInputRef = element => {
    console.log("element",element);
    this.textInput = element;
  };

green = () =>{
  console.log("green ",this.textInput);
/*   this.textInput.current.style.backgroundColor = "green"; */
  this.textInput.style.backgroundColor = "green";
}

red = () =>{
  console.log("red ",this.textInput);
/*   this.textInput.current.style.backgroundColor = "red"; */
  this.textInput.style.backgroundColor = "red";
}
  
  render() {
    return (
      <div>
      {/* 
      <span id="green" ref={input => { this.setTextInputRef = input; }}>Green</span><br/>
      <span id="red" ref={input => { this.setTextInputRef = input; }}>Red</span><br/> 
      */}
      <span id="green" ref={this.setTextInputRef}>Green</span><br/>
      <span id="red" ref={this.setTextInputRef}>Red</span><br/>
      <button onClick={this.green}>For Green</button><br/>
      <button onClick={this.red}>For Red</button><br/>
      </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))