1const FancyButton = React.forwardRef((props, ref) => (
2 <button ref={ref} className="FancyButton">
3 {props.children}
4 </button>
5));
6
7// You can now get a ref directly to the DOM button:
8const ref = React.createRef();
9<FancyButton ref={ref}>Click me!</FancyButton>;
1const FocusDemo = () => {
2
3 const [inputRef, setInputFocus] = useFocus()
4
5 return (
6 <>
7 <button onClick={setInputFocus} >
8 FOCUS
9 </button>
10 <input ref={inputRef} />
11 </>
12 )
13
14}
15
16const useFocus = () => {
17 const htmlElRef = useRef(null)
18 const setFocus = () => {htmlElRef.current && htmlElRef.current.focus()}
19
20 return [ htmlElRef, setFocus ]
21}
22
1
2class Lesson9Refs extends Component {
3
4 onAddProduct = () => {
5 alert(this.refs.productname.value);
6 }
7
8
9 return (
10
11 <div>
12
13 <div className="container">
14 <div class="card mt-10">
15 <div class="card-header">
16 Featured
17 </div>
18 <div class="card-body">
19
20 <label> Product Name: </label>
21 <input type='text' className="form-control" ref="productname" />
22
23 <button type="submit" className="btn btn-primary" onClick={ this.onAddProduct } >
24 Add Product
25 </button>
26
27 </div>
28 </div>
29 <div className="row mt-10">
30 { elements }
31 </div>
32 </div>
33 </div>
34 );
35
36 }
37}
38
39export default Lesson9Refs;
1// bad
2<Foo
3 ref="myRef"
4/>
5
6// good
7<Foo
8 ref={(ref) => { this.myRef = ref; }}
9/>
10
1class MyComponent extends React.Component {
2 constructor(props) {
3 super(props);
4 this.myRef = React.createRef(); }
5 render() {
6 return <div ref={this.myRef} />; }
7}