React forwardRef

by jonahe

HTML

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

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

.done {
  color: rgba(0, 0, 0, 0.3);
  text-decoration: line-through;
}

input {
  margin-right: 5px;
}

React

class CustomInput extends React.Component {
	constructor(props) {
  	super(props);
    this.state = {value: "initial value"};
    
  }
  render() {
  	return (
    	<div>
        <input 
          type="text" 
          ref={this.props.forwardedRef} 
          value={this.state.value}
          onChange={(e) => this.setState({value: e.target.value})}
         />
         <button onClick={ () => this.setState({value: ""}) }>Clear input</button>
      </div>
    )
  }
};

const ForwardedRefInput = React.forwardRef((props, ref) => {
	return (
  	<CustomInput forwardedRef={ref} {...props} />
  );
});

class App extends React.Component {
  constructor(props) {
    super(props);
    this.customInputRef = React.createRef();
  }
  
  render() {
  	console.log("inputRef", this.customInputRef);
    return (
      <div>
        <button onClick={ () => this.customInputRef.current.focus() }>Focus input through ref</button>
        <ForwardedRefInput ref={this.customInputRef} />
      </div>
    )
  }
}
console.log(React)

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