Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  60] [ 5]  / answers: 1 / hits: 89011  / 6 Years ago, sun, august 5, 2018, 12:00:00

I was trying to do this.



I must be missing something, but I don't understand why current is always null in this example.



class App extends React.PureComponent {
constructor(props) {
super(props);
this.test = React.createRef();
}
render() {
return <div className=App>current value : {this.test.current + }</div>;
}
}


You can check my test case here


More From » reactjs

 Answers
12

Because you forgot to assign the ref to some dom element. You are only creating it.


Write it like this:


class App extends React.PureComponent {
constructor(props) {
super(props);
this.test = React.createRef();
}

handleClick = () => alert(this.test.current.value)

render() {
return (
<div className="App">
<input ref={this.test} />
<button onClick={this.handleClick}>Get Value</button>
</div>
)
}
}

Working Example.


[#53807] Tuesday, July 31, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;