Sunday, April 22, 2018

React 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 string refs we set the ref attribute to a name (string) and later access the element/component using the referenced name.

In this example let us see how to use a string ref to access the content in a textbox and display it in the screen. In this example we create a ref with name refName for the text control (ref="refName"). In the onChange() event of the control we get the content of the textbox using the ref and display it in the screen.



Make sure to include the required libraries like react, react-dom, bable etc. In this example i am using my local files, you can use your local files or use an appropriate CDN link to refer these libraries.

<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.refs.refName.value});
                },
                render: function () {
                    return (
                        <div>
                            <input type="text" ref="refName" 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>

Search Flipkart Products:
Flipkart.com

No comments: