Our Global Presence
Canada
57 Sherway St,
Stoney Creek, ON
L8J 0J3
India
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
USA
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
We love React!! We have been using the latest stuff from React in our latest project and found a lot of important and cool differences from the previous versions.
The following APIs will not only help you increase your productivity but also improve your code structure.
Any developer who is looking forward to learn React or even the ones who have been using React for a while should be able to use and enjoy the stuff in this article!!
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'; function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="users/*" element={<Users />} /> </Routes> </BrowserRouter> ); } function Users() { /* All <Route path> and <Link to> values in this component will automatically be "mounted" at the /users URL prefix since the <Users> element is only ever rendered when the URL matches /users/* */ return ( <div> <nav> <Link to="me">My Profile</Link> </nav> <Routes> <Route path="/" element={<UsersIndex />} /> <Route path=":id" element={<UserProfile />} /> <Route path="me" element={<OwnUserProfile />} /> </Routes> </div> ); }
The above is standard code that is used to created routes for navigation in React projects.
Now let’s check React router v6 code:
import { BrowserRouter, Routes, Route, Link, Outlet } from 'react-router-dom'; function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="users" element={<Users />}> <Route path="/" element={<UsersIndex />} /> <Route path=":id" element={<UserProfile />} /> <Route path="me" element={<OwnUserProfile />} /> </Route> </Routes> </BrowserRouter> ); } function Users() { return ( <div> <nav> <Link to="me">My Profile</Link> </nav> <Outlet /> </div> ); }
The <Outlet> element is used as a placeholder. In this case an <Outlet>enables the Users component to render its child routes. Thus the<Outlet> element will render either a <UserProfile> or <OwnUserProfile> element depending on the current location.
Thus the best way this element can be used is in layouts. You can simply create multiple layouts, for e.g.- the Dashboard Layout(for the profile and members page) or the Main Layout(for login and logout, basically when the user is not signed in). Finally, you can simply inject whichever component one needs depending on its route rather than wrapping each route component in a parent layout component like:
<Route path="/" element={<DashboardLayout />}> <Route path="/" element={<HomePage />} /> <Route path=":id" element={<UserProfile />} /> <Route path="me" element={<OwnUserProfile />} /> </Route>
import { BrowserRouter, Link, Outlet, useRoutes } from 'react-router-dom'; function App() { // The <BrowserRouter> element is removed from App because the // useRoutes hook needs to be in the context of a <BrowserRouter> // element. This is a common pattern with React Router apps that // are rendered in different environments. To render an <App>, // you'll need to wrap it in your own <BrowserRouter> element. let element = useRoutes([ // A route object has the same properties as a <Route> // element. The `children` is just an array of child routes. { path: '/', element: <Home /> }, { path: 'users', element: <Users />, children: [ { path: '/', element: <UsersIndex /> }, { path: ':id', element: <UserProfile /> }, { path: 'me', element: <OwnUserProfile /> }, ] } ]); return element; } function Users() { return ( <div> <nav> <Link to="me">My Profile</Link> </nav> <Outlet /> </div> ); }
React Router v6 ships with an awesome API for routing that uses plain JavaScript objects to declare your routes. In fact, if you look at the source of <Routes>, you’ll see that it’s really just a tiny wrapper around a hook that is at the heart of the router’s matching algorithm: useRoutes.
The useRoutes hook is a first-class API for routing that lets you declare and compose your routes using JavaScript objects instead of React elements. Continuing with the example above, let’s see what it looks like with useRoutes.
The useRoutes hook accepts a (possibly nested) array of JavaScript objects that represent the available routes in your app. Each route has a path, element, and (optionally) children, which is just another array of routes.
This nested array of Javascript objects keeps the code DRY and improves the readability of the code.
The object-based route configuration may look familiar if you were using the react-router-config package in v5. In v6, this configuration format has been promoted to a first-class API in core and the react-router-config package will be deprecated.
Moreover, the layout example in the Outlet section can be simplified as follows:
let element = useRoutes([ { path: '/', element: <DashboardLayout/>, children: [ { path: '/', element: <HomePage/> }, { path: ':id', element: <UserProfile /> }, { path: 'me', element: <OwnUserProfile /> }, ] } ]);
Ref forwarding is a cool technique for automatically passing a ref through a component to one of its 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.
Before We show you how to ‘forward’ refs lets first learn what they are and how to create them.
To create a ref, use the React function called React.createRef(). These refs can then be attached to React elements via the ref attribute. Refs are somewhat similar to state. On assigning refs to instance properties of that component we can ensure that they can be referenced anywhere in the component. Check the example below:
class MyComponent extends React.Component { constructor(props) { super(props); this.newRef = React.createRef(); //newRef is now available for use throughout our component } ... } class MyComponent extends React.Component { ... render() { return <div ref={this.myRef} />; } }
Here We created a ref called newRef and and attached it to the div element in the MyComponent component. As a result, We now have the ability to update the div without changing state.
This is the significance of using refs as you can update and modify elements without using state variables that result in the re-rendering of components.
A few points of significance directly from the documentation:
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, you can use refs to control the state of music or video players (pause, play, stop) without them re-rendering anytime you 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 you 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, you can target that particular node and increment it every time a user clicks the button without causing a re-render and finally, you can send one request to our server with the final value.
You 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.
Now let’s move to the technique of ref forwarding:
Ref forwarding is a technique that automatically passes a ref through a component to one of its children. Ref forwarding is very useful when building reusable component libraries. forwardRef is the function used to pass the ref to a child component. Let’s check out an example below:
function SampleButton(props) { return ( <button className="button"> {props.children} </button> ); }
The SampleButton() component is a modified button that will 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:
We have just covered the basics of these very extensive topics. Hope you try them out in your coming React projects.
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
React Router is by far the most popular library in the React ecosystem. According to npm, it is downloaded about 3.6 million times a week. This number is almost half of React’s 7.6 million weekly downloads. This means that almost every second project that uses React uses React Router.
That’s huge. Almost half of the React projects out there rely on React Router for routing. Chances are, if you have worked with React, you have worked with React Router.
Now with version six in beta and a new release coming soon, we thought it would be interesting to take a dive into what’s new and what has changed in React Router version 6.
For a library that is so important to the React community, it has gone through a number of iterations and breaking changes. From its first release in 2014, and with every major release, the maintainers of React Router have introduced new features and breaking changes. Some in the React community have complained about the difficulty of upgrading from one version to the next, and have questioned the library’s constant churn.
Many have complained about the difficult upgrades that came with every new major release of the library.
If your application is working correctly, and you don’t need access to the new features promised in version 6, you can stick with your older version. Don’t feel the need to refactor your old applications to use React Router 6. If it ain’t broke, don’t fix it.
npm install react-router@next react-router-dom@next
So without further ado, let’s take a look at what’s new and what has changed in the latest version of React Router
Routes is introduced as a new element in React Router version 6. This new element allows us to easily define nested routes and relative routes, and make it easy to compose complex routes and layouts. In the previous version of the library, we defined Routes inside of a Switch.
The <Routes > is the new <Switch> element now. It is very much similar to <Switch> with some new features.
// old - v5 import { BrowserRouter, Switch, Route } from 'react-router-dom'; const App = () => { return ( <BrowserRouter> <Switch> <Route exact path="/" component={Home} /> <Route path="/users" component={Users} /> </Switch> </BrowserRouter> ); } // new - v6 import { BrowserRouter, Routes, Route } from 'react-router-dom'; const App = () => { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="users" element={<Users />} /> </Routes> </BrowserRouter> ); }
Did that component prop got changed to element?
That brings us to our second highlight.
If you notice in the above example, in the new version we are passing a react element instead of a component. This is so much better, now we can pass props directly to the element.
// old - v5 <Route exact path="/" component={Home} /> <Route path="/users" render={routeProps => ( <Users isCustomLayout={true} /> )} /> // new - v6 <Route path="/" element={<Home />} /> <Route path="users" element={<Users isCustomLayout={true} />} />
Now, all Route and Link children of a Route are relative to their parent. This makes it a lot easier to build applications with many nested routes and makes it easier to reason about your application’s routing logic.
No more exact and strict props
Yes, you read it right. In v6 all the routes match exactly by default.
// old - v5 <Route exact path="/" component={Home} /> // new - v6 <Route path="/" element={<Home />} />
Relative paths and links
In v6, both paths and links are relative to their parent route. This means we can omit the “/” if we want the relative path.
// old - v5 <Route exact path="/" component={Home} /> <Route path="/users" component={Users} /> // new - v6 <Route path="/" element={<Home />} /> <Route path="users" element={<Users />} />
If you have used previous versions of React Router, you will immediately notice that we don’t need to use the exact prop anymore. You will also notice that the Link we defined is relative. Instead of passing /customers/:id, we can just use /:id.
What about nested routes then? They just got better.
Just like your regular react elements we just need to wrap the child route with a parent one.
// old - v5 <Route exact path="/" component={Home} /> <Route path="/users" component={Users} /> // .... users.js import { useRouteMatch } from 'react-router-dom'; const Users = () => { const { path } = useRouteMatch(); return ( <div> // you can do something here <Switch> <Route path={`${path}/:id`} component={UserInfo} /> <Route path={`${path}/profile`} component={UserProfile} /> </Switch> </div> ); } // new - v6 <Route path="/" element={<Home />} /> <Route path="users" element={<Users />}> <Route path=":id" element={<UserInfo />} /> <Route path="profile" element={<UserProfile />} /> </Route> // .... import { Outlet } from 'react-router-dom'; const Users = () => { return ( <div> // you can do something here // Outlet: This element is used as a placholder for the child route. // Which means it will be either <UserInfo /> or <UserProfile /> <Outlet /> </div> ); }
Now we can define our routes using the new useRouter hook. This allows you to build your routes using JavaScript objects. Let’s take a look at our previous application, now defined using useRouter.
import { BrowserRouter, Link, Outlet, useRoutes } from 'react-router-dom'; function App() { let element = useRoutes([ { path: '/', element: <Home /> }, { path: 'customers', element: <Customers />, children: [ { path: '/', element: <CustomersIndex /> }, { path: ':id', element: <CustomerProfile /> }, ] } ]); return element; } function Users() { return ( <div> <nav> <Link to="/1">Customer 1</Link> </nav> <Outlet /> </div> ); }
You might ask yourself, why does it matter? Why would I want to compose my routes using JavaScript objects instead of JSX? One great use case would be to programmatically build routes, let’s say, based on the directory structure of your application. You could loop through all of the files in your pages directory, and build routes from that.
The team behind React Router claims that the new version is a lot smaller than the previous versions. They estimate that it’s about 70% smaller. Smaller bundles mean that your application loads faster, and content to your users faster.
With all these awesome changes, there is also icing on the cake. They have reduced the bundle size by more than 50%.
The old useHistory hook has been removed and replaced with a suspense-ready navigate API. Now you can use useNavigate to programmatically navigate around your application. They also expose a Navigate component that you can use to redirect your users.
No more history, it’s time to navigate. The useHistory hook is now replaced with the suspense-ready useNavigate hook.
// old - v5 import { useHistory } from 'react-router-dom'; const CustomButton = props => { const history = useHistory(); const handleClick = () => { history.push('/users'); } return <button onClick={handleClick}>{props.label}</button>; } // new - v6 import { useNavigate } from 'react-router-dom'; const CustomButton = props => { const navigate = useNavigate(); const handleClick = () => { navigate('/users'); } return <button onClick={handleClick}>{props.label}</button>; }
So that’s it! If you believe that your applications can benefit from smaller bundle sizes, and from suspense ready navigation, we strongly suggest that you upgrade to the latest version.
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
© 2024 — HK Infosoft. All Rights Reserved.
© 2024 — HK Infosoft. All Rights Reserved.
T&C | Privacy Policy | Sitemap