1573444117
Ref forwarding in React is a feature that lets components pass down (“forward”) refs to their children. It gives the child component a reference to a DOM element created by its parent component. This then allows the child to read and modify that element anywhere it is being used.
In this tutorial, we will go over the concept of forwarding refs in React and understand how it helps us manage interactions with the DOM. For a more engaging experience, we’ll cover how to create refs, attach created refs to DOM elements and classes, forward refs, and so on.
It is also worthy to note that we will often make references to the docs page to build on the information that already exists and prove our concepts with relatable real-life examples and snippets to be hosted on CodeSandbox.
To understand Ref forwarding, we must first understand what refs are, how they work, and go over a few use cases. Typically in React, parent components pass data down to their children via props.
To change the behavior of a child component you render it with a new set of props. To modify a child component such that it exhibits a slightly different behavior, we need a way to make this change without reaching for the state or re-rendering the component.
We can achieve this by using refs. With refs, we have access to a DOM node that is represented by an element. As a result, we can modify it without touching its state or re-rendering it.
Since refs hold a reference to the DOM element itself, we can manipulate it with native JavaScript functions that are unavailable in the React library. For instance, we can initiate focus on input field when a button is clicked:
import ReactDOM from "react-dom";
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.myInput = React.createRef();
}
render() {
return (
<div>
<input ref={this.myInput} />
<button
onClick={() => {
this.myInput.current.focus();
}}
>
focus!
</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You can also find the code at CodeSandbox:
To implement this with pure JavaScript we could do something like this:
document.getElementById('input').focus
Through the ref, we manipulated our cursor to automatically focus on the input element whenever the button is clicked. Without refs, we’d have to use state to check if the input field should focus or not — that is before making a decision, which is often unnecessary in cases like this.
As seen in the official React documentation, there are a few good use cases for refs:
Let’s imagine you have an input component. In some parts of your application, you may want the cursor focused on it when a user clicks a button. It makes more sense to modify only that particular instance of the input component without changing the state (via refs), rather than changing the state (via props) which will cause the component to re-render every-time. Similarly, we can use refs to control the state of music or video players (pause, play, stop) without them re-rendering anytime we click a button (change the state).
Think about a Medium clap button. A quick way to implement a similar feature would be to increment the count value stored in the state every time a user clicks a clap. However, this may not be very efficient. Every time a user clicks the clap button it will re-render, and if we are sending a network request to store the value in a server it will get sent as many times as the button is clicked. With refs, we can target that particular node and increment it every time a user clicks the button without causing a re-render and finally, we can send one request to our server with the final value.
We can use refs to trigger animation between elements that rely on themselves for their next state but exist in different components (this concept is called ref forwarding). Refs can also be used to simplify integration with third-party DOM libraries and managing multistep form value states etc.
To create a ref, React provides a function called React.createRef()
. Once created they can be attached to React elements via the ref attribute. It is also worthy to note that refs are somewhat similar to state. When a component is constructed, refs get assigned to instance properties of that component ensuring that they can be referenced anywhere in the component:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.newRef = React.createRef(); //newRef is now available for use throughout our component
}
...
}
At this point, we have created a Ref called newRef
. To use this Ref in our component, we simply pass it as a value to the ref
attribute like this:
class MyComponent extends React.Component {
...
render() {
return <div ref={this.myRef} />;
}
}
We’ve attached the Ref here and passed in the newRef
as it’s value. As a result, we now have the ability to update this without changing state.
Refs are created when a component is rendered and can be defined either in the componentDidMount()
or in the constructor()
. As such, they can be attached to DOM elements or class components but cannot be attached to function components because they don’t have instances.
Every Ref you define will represent a node in the DOM. Hence, when you want to reference that node in a render()
function, React provides a current
attribute that references the said node.
const DOMNode = this.newRef.current; // refers to the node it represents
The value of the ref differs depending on the type of the node it references (class components or DOM elements).
For a better understanding of refs and type of node they reference, and the default values associated with each, let’s consider this piece from the documentation:
React.createRef()
receives the underlying DOM element as its current
propertycurrent
i.e the components props, state, and methodsLet’s demonstrate this concept with a small video player. The video player will have some pause and play functionalities. To build along, create a new CodeSandbox project and add the following code:
import ReactDOM from "react-dom";
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.myVideo = React.createRef();
}
render() {
return (
<div>
<video ref={this.myVideo} width="320" height="176" controls>
<source
src="https://res.cloudinary.com/daintu6ky/video/upload/v1573070866/Screen_Recording_2019-11-06_at_4.14.52_PM.mp4"
type="video/mp4"
/>
</video>
<div>
<button
onClick={() => {
this.myVideo.current.play();
}}
>
Play
</button>
<button
onClick={() => {
this.myVideo.current.pause();
}}
>
Pause
</button>
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You can also find the code here:
Here, we used ref to pause and play our video player by calling the pause and play methods on the video. When the pause or play button is clicked, the function will be called on the video player without a re-render.
Refs cannot be attached to function components. Although, we can define refs and attach them to either DOM elements or class components. The bottom line is — function components do not have instances so you can’t reference them.
However, if you must attach a ref to a function component, the official React team recommends that you convert the component to a class, just like you would do when you need lifecycle methods or state.
Aside from passing the default ref
attribute, we can also pass functions to set refs. The major advantage of this approach is that you have more control over when refs are set and unset. That is possible because it gives us the ability to determine the state of the ref before certain actions are fired. Consider this snippet from the documentation page below:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = null;
this.setTextInputRef = element => {
this.textInput = element;
};
this.focusTextInput = () => {
// Focus the text input using the raw DOM API
if (this.textInput) this.textInput.focus();
};
}
componentDidMount() {
this.focusTextInput();
}
render() {
return (
<div>
<input
type="text"
ref={this.setTextInputRef}
/>
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
Instead of defining the refs in the constructor, we set the initial value to be null. The benefit of this approach is that textInput
will not reference a node until the component is loaded (when the element is created).
When a child component needs to reference its parent components current node, the parent component needs a way to send down its ref to the child. The technique is called ref forwarding.
Ref forwarding is a technique for automatically passing a ref through a component to one of its children. It’s very useful when building reusable component libraries. forwardRef
is a function used to pass the ref to a child component:
function SampleButton(props) {
return (
<button className="button">
{props.children}
</button>
);
}
The SampleButton()
component will tend to be used throughout the application in a similar manner as a regular DOM button, therefore accessing its DOM node may be unavoidable for managing focus, selection, or animations related to it.
In the example below, SampleComponent()
uses React.forwardRef
to obtain the ref passed to it, and then forward it to the DOM button that it renders:
const SampleButton = React.forwardRef((props, ref) => (
<button ref={ref} className="button">
{props.children}
</button>
));
const ref = React.createRef();
<SampleButton ref={ref}>Click me!</SampleButton>;
Now that we’ve wrapped the SampleButton
component with the forwardRef
method, components using it can get a ref to the underlying button DOM node and access it if necessary —just like if they used a DOM button directly.
Here’s a clarification for the code above:
<button ref={ref}>
by specifying it as a JSX attributeref.current
will point to the <button>
DOM nodeThe second ref argument in the SampleButton component only exists when you define a component with
React.forwardRef
call
Regular function or class components don’t receive the ref argument, and ref is not available in props either
Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too
Using refs will definitely make our React code better as we will be more decisive in how we manage our state, props, and re-rendering. In this tutorial, we’ve covered the basics of refs and ref forwarding. We also looked at a few use cases and a few ways we can call refs. To read more about refs check out the docs here.
#React #javascript #web-development
1598839687
If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?
In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.
Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.
React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.
Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.
Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.
The popularity of React Native comes from its advantages. Some of its advantages are as follows:
Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.
React Native is very close to native. Consider the following aspects as described on the React Native website:
Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.
#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native
1607768450
In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/
#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks
1615544450
Since March 2020 reached 556 million monthly downloads have increased, It shows that React JS has been steadily growing. React.js also provides a desirable amount of pliancy and efficiency for developing innovative solutions with interactive user interfaces. It’s no surprise that an increasing number of businesses are adopting this technology. How do you select and recruit React.js developers who will propel your project forward? How much does a React developer make? We’ll bring you here all the details you need.
Facebook built and maintains React.js, an open-source JavaScript library for designing development tools. React.js is used to create single-page applications (SPAs) that can be used in conjunction with React Native to develop native cross-platform apps.
In the United States, the average React developer salary is $94,205 a year, or $30-$48 per hour, This is one of the highest among JavaScript developers. The starting salary for junior React.js developers is $60,510 per year, rising to $112,480 for senior roles.
In context of software developer wage rates, the United States continues to lead. In high-tech cities like San Francisco and New York, average React developer salaries will hit $98K and $114per year, overall.
However, the need for React.js and React Native developer is outpacing local labour markets. As a result, many businesses have difficulty locating and recruiting them locally.
It’s no surprise that for US and European companies looking for professional and budget engineers, offshore regions like India are becoming especially interesting. This area has a large number of app development companies, a good rate with quality, and a good pool of React.js front-end developers.
As per Linkedin, the country’s IT industry employs over a million React specialists. Furthermore, for the same or less money than hiring a React.js programmer locally, you may recruit someone with much expertise and a broader technical stack.
React is a very strong framework. React.js makes use of a powerful synchronization method known as Virtual DOM, which compares the current page architecture to the expected page architecture and updates the appropriate components as long as the user input.
React is scalable. it utilises a single language, For server-client side, and mobile platform.
React is steady.React.js is completely adaptable, which means it seldom, if ever, updates the user interface. This enables legacy projects to be updated to the most new edition of React.js without having to change the codebase or make a few small changes.
React is adaptable. It can be conveniently paired with various state administrators (e.g., Redux, Flux, Alt or Reflux) and can be used to implement a number of architectural patterns.
Is there a market for React.js programmers?
The need for React.js developers is rising at an unparalleled rate. React.js is currently used by over one million websites around the world. React is used by Fortune 400+ businesses and popular companies such as Facebook, Twitter, Glassdoor and Cloudflare.
As you’ve seen, locating and Hire React js Developer and Hire React Native developer is a difficult challenge. You will have less challenges selecting the correct fit for your projects if you identify growing offshore locations (e.g. India) and take into consideration the details above.
If you want to make this process easier, You can visit our website for more, or else to write a email, we’ll help you to finding top rated React.js and React Native developers easier and with strives to create this operation
#hire-react-js-developer #hire-react-native-developer #react #react-native #react-js #hire-react-js-programmer
1627031571
The most awaited version of React 18 is finally out now. Its team has finally revealed the alpha version of React 18 and its plan, though the official launch is still pending. This time the team has tried something and released the plan first to know their user feedback because the last version of React 17 was not that much appreciated among developers.
According to Front-end Frameworks Survey, React JS has ranked top in the list of most loved frameworks. Thus, the developer communities expect a bit higher from the framework, so they are less appreciative of the previous launch.So, this time React 18 will be a blast. For beginners, the team is working on a new approach. They have called a panel of experts, library authors, educators, and developers to take part in a working group. Initially, it will be a small group.
I am not a part of this release but following the team on their GitHub discussion group. After gathering the information from there, I can say that they have planned much better this time.
React 17 was not able to meet the developer's community. The focus was all primarily centered on making it easier to upgrade React itself. React 18 release will be the opposite. It has a lot of features for react developers.
#hire react js developers #hire react js developers india #react developers india #react js developer #react developer #hire react developers
1589722410
As we start learning new technologies we want to start building something or work on a simple project to get a better understanding of the technology. So, let’s build this simple app.
For this app, we will be using PokeApi to get our pokemon data, and also we will be using Hooks. I am using pokemondb for pokemon sprites. It’s just a personal preference you can use whatever you want.
#react-native #react-native-app #react-navigation #react-native-development #react