Created
July 7, 2018 07:56
-
-
Save namtx/7be66d300c1d394d9f534b5c055ebcef to your computer and use it in GitHub Desktop.
React `ref` with `HOC`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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