Monday, April 30, 2018

React callback ref example

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.

        <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: !});
                onNameChange: function(event) {
                    this.setState({name: this.callbackRef.value});
                setCallbackRef: function(element){
                    this.callbackRef = element;
                render: function () {
                    return (
                            <input type="text" ref={this.setCallbackRef} onChange={this.onNameChange}/>             
                            <span>Hello <b>{} !!!</b></span>

                <HelloRefs greetingsText="Hello"/>, document.getElementById('root')
        <div id="root"/>

Search Flipkart Products:

No comments: