Sunday, April 22, 2018

React ref for components 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.

Refs can be used to get a handle to HTML elements like textbox, dropdown etc, or get handles to other react components in the page.

In this example let us see how to use a string ref to set focus to another component in the screen. In this example we have 2 components HelloRefComponent is the parent component and HelloChildComponent is the child component. We create a ref (ref="refComponent") to the child component and use it in the parent component to set the focus on the child component. We use ReactDOM.findDOMNode to get the instance of the child component and set the focus.


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.

        <script src="script/react.js"></script>
        <script src="script/react-dom.js"></script>
        <script src="script/browser.js"></script>
        <script type="text/babel">
            var HelloRefComponent = React.createClass({
                onClick: function(event) {
                    var compInstance = ReactDOM.findDOMNode(this.refs.refComponent);
                render: function () {
                    return (
                            <div style={{height:'900px', width: '200px', display:'block', backgroundColor:'silver'}}>
                                <span>Hello from Parent Component</span><br/>
                                    value="Click to view Child Component"
                                <HelloChildComponent ref="refComponent"/>   
            var HelloChildComponent = React.createClass({
                render: function () {
                    return (
                        <div style={{height:'100px', width: '200px', display:'block', backgroundColor:'wheat'}}>
                            <span>Hello from Child component</span>

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

Search Flipkart Products:

No comments: