Refs in React is a shortcut way to access a specific DOM node or a React component.
There are two types of refs in react, string refs and callback refs.
In callback refs we set the ref attribute to a function which receives the component/element reference as an argument and sets the reference.
In this example let us see how to use a callback ref to read the text from a textbox and display it on the page.
<html>
<head>
<script src="script/react.js"></script>
<script src="script/react-dom.js"></script>
<script src="script/browser.js"></script>
<script type="text/babel">
var HelloRefs = React.createClass({
getInitialState: function() {
return {show: false, name: ""}
},
onClick: function() {
this.setState({show: !this.state.show});
},
onNameChange: function(event) {
this.setState({name: this.callbackRef.value});
},
setCallbackRef: function(element){
this.callbackRef = element;
},
render: function () {
return (
<div>
<input type="text" ref={this.setCallbackRef} onChange={this.onNameChange}/>
<span>Hello <b>{this.state.name} !!!</b></span>
</div>
);
}
});
ReactDOM.render(
<HelloRefs greetingsText="Hello"/>, document.getElementById('root')
);
</script>
</head>
<body>
<div id="root"/>
</body>
</html>
There are two types of refs in react, string refs and callback refs.
In callback refs we set the ref attribute to a function which receives the component/element reference as an argument and sets the reference.
In this example let us see how to use a callback ref to read the text from a textbox and display it on the page.
<html>
<head>
<script src="script/react.js"></script>
<script src="script/react-dom.js"></script>
<script src="script/browser.js"></script>
<script type="text/babel">
var HelloRefs = React.createClass({
getInitialState: function() {
return {show: false, name: ""}
},
onClick: function() {
this.setState({show: !this.state.show});
},
onNameChange: function(event) {
this.setState({name: this.callbackRef.value});
},
setCallbackRef: function(element){
this.callbackRef = element;
},
render: function () {
return (
<div>
<input type="text" ref={this.setCallbackRef} onChange={this.onNameChange}/>
<span>Hello <b>{this.state.name} !!!</b></span>
</div>
);
}
});
ReactDOM.render(
<HelloRefs greetingsText="Hello"/>, document.getElementById('root')
);
</script>
</head>
<body>
<div id="root"/>
</body>
</html>
No comments:
Post a Comment