Skip to content

Instantly share code, notes, and snippets.

@namtx
Created July 7, 2018 07:56
Show Gist options
  • Save namtx/7be66d300c1d394d9f534b5c055ebcef to your computer and use it in GitHub Desktop.
Save namtx/7be66d300c1d394d9f534b5c055ebcef to your computer and use it in GitHub Desktop.
React `ref` with `HOC`
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import InputField from "./FancyInput";
class App extends Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
// this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<InputField ref={this.textInput} />
);
}
}
export default App;
import React from "react";
const TextInput = ({forwardRef, children, ...rest}) => {
return (
<div>
<input ref={forwardRef} {...rest} />
{children}
</div>
)
}
// HOC
const Input = InputComponent => {
const forwardRef = (props, ref) => {
const onType = (e) => console.log(ref.current.value);
return <InputComponent forwardRef={ref} onChange={onType} {...props}/>
}
return React.forwardRef(forwardRef);
}
const InputField = Input(TextInput);
export default InputField;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment