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
Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and returns HTML via a render function. In this article, we will be looking at five React components that are useful in upcoming year as listed below.
Grommet is component library intended to help you in the task of creating your own websites simply by mixing and matching parts. That being said, this one has a strong focus on accessibility (by providing features such as keyword navigation, screen reader tags and so on), responsiveness and theming.
And if you’re not designed-inclined, which some developers aren’t they even provide you with a design kit and a complete icon set.
The design kit comes in different flavors such as Sketch for MacOS (seen in the screenshot below), Adobe XD and more.
Finally, the icon set can be seen in full on their site, but the image below shows how easy it is to install them into your project and add them to your code.
Much like the React Spinner, React Virtualized is meant to solve a single problem: efficiently rendering lists and tabular data in your pages.
Those edge cases and others are the ones this particular project is attempting to tackle.
Their website has a very simple, yet powerful demo you can play around with and understand the power this library brings to the mix. Change the numbers around and add copious amount of elements to your lists and see how easy it can adapt. Then think about how much code you’d have to write to make your own lists as flexible and then download React Virtualized.
react-desktop is a JavaScript library built on top of Facebook’s React library, which aims to bring a native desktop experience to the web, featuring many macOS Sierra and Windows 10 components. react-desktop works perfectly with NW.js and Electron.js, but can be used in any JavaScript powered project!
Take a look at the following screenshots to understand what we mean by that.
As you can see, with this library you can perfectly reproduce the desktop experience using JavaScript, which means you can create actual desktop applications using Electron.js or just add a very interesting look&feel to your web apps.
If you’re looking for an easy way to develop desktop applications using web technologies, we highly recommend doing so with React Desktop and Electron.js.
To build your own team’s library, without tons of overhead, try using Bit.dev. If a component library is like a music CD-Album, then bit.dev is like iTunes or Spotify for UI components. It kills 90% of the overhead, it’s scalable and it provides many enhanced features for shared components:
Here’s a short example, using a simple to-do app:
git clone https://github.com/giteden/basic-todo-app.git
Let’s say we want to export our app’s components to a shared collection (library)
Initialize a workspace and log in:
$ cd basic-todo-app
$ bit init
$ bit login
Add (all) components:
$ bit add src/components/*
Configure a React compiler (components are built independent of your project’s build configurations) :
$ bit import bit.envs/compilers/react --compiler
Tag and export to a shared collection (create your own collection in bit.dev):
$ bit tag --all 1.0.0
$ bit export username.collection
Rebass is a tiny UI components library capable of creating a very powerful set of themeable UI elements based on the Styled System library.
Some of the key features of this library are:
For more Information and to build a website 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 your custom website using React JS, please visit our technology page.
Content Source:
Hooks are quite possibly the most eagerly awaited addition to React since the rewrite. Does the product live up to the hype? From my perspective, yes, as they really are a great feature. They are essentially functions that open up new opportunities, such as:
There are few React hooks that are included as default. The three basic ones are useState, useEffect, and useContext. There are also several additional ones, e.g., useRef and useMemo, but for now, we shall focus on the basics.
Let’s take a look at useState, and let’s use it to create an example of a straightforward counter. How does it work? Well, basically, the whole construct is really straightforward and looks like:
export function Counter() { const [counter, setCounter] = React.useState(0); return ( <div> {counter} <button onClick={() => setCounter(counter + 1)}>+</button> </div> ); };
It is invoked with initialState (value) and returns an array with two elements with it. Thanks to array destructuring assignment, we can assign the variables to these elements right away. The first one is always the last state after updates, while the other one is a function that we will use to update the value. Seems rather easy, doesn’t it?
Also, due to the fact that such components used to be called stateless functional components, such a name is not appropriate anymore, because they can have a state as it is shown above. Hence, the names class components and function components seem to be more in line with what they actually do, at least from 16.8.0.
The update function (in our case setCounter), can also be used as a function which will take the previous value as an argument in the following form:
<button onClick={() => setCounter(prevCounter => prevCounter + 1)}>+</button> <button onClick={() => setCounter(prevCounter => prevCounter - 1)}>-</button>
However, unlike the this.setState class component which was doing a shallow merge, setting the function (setCounter in our case) is overriding the whole state instead.
In addition, initialState can also be a function, not just a plain value. This has its own benefits, as that function will be run only during the initial render of the component and after that, it won’t be invoked anymore.
const [counter, setCounter] = useState(() => calculateComplexInitialValue());
Finally, if we are going to use setCounter with the exact same value that we had at the very same moment in the current state (counter), then component will not rerender.
On the other hand, useEffect is about adding side effects to our functional component, be it subscriptions, API calls, timers, or just about anything that we may find useful. Any function that we will pass to useEffect will be run after render, and it will be doing so after every render unless we add a limitation concerning what properties’ changes should be rerun as a second argument of the function. If we want to run it only on mount and clean up on unmount, then we just need to pass an empty array in it.
const fetchApi = async () => { const value = await fetch("https://jsonplaceholder.typicode.com/todos/1"); console.log(await value.json()); }; export function Counter() { const [counter, setCounter] = useState(0); useEffect(() => { fetchApi(); }, []); return ( <div> {counter} <button onClick={() => setCounter(prevCounter => prevCounter + 1)}>+</button> <button onClick={() => setCounter(prevCounter => prevCounter - 1)}>-</button> </div> ); };
The above code will be only run once due to an empty array as a second argument. Basically, it is something like componentDidMount in such case, but it fires a bit later. If you want to have a similar hook that is called before browser paint, use useLayoutEffect, but these updates will be applied synchronously, unlike useEffect.
useContext seems to be the easiest to understand, as one provides to which context we want to get access (an object that was returned by the createContext function) and in return, it provides us with the value for that context.
const context = useContext(Context);
Finally, to write your own hook, you can just write something like the following:
function useWindowWidth() { let [windowWidth, setWindowWidth] = useState(window.innerWidth); function handleResize() { setWindowWidth(window.innerWidth); } useEffect(() => { window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return windowWidth; }
Basically, we are using the regular useState hook for which we are assigning as initial value window width. Then in useEffect, we are adding a listener which will trigger handleResize on each window resize. We also clear after component will be unmounted (look at the return in useEffect). Easy?
Note: The word used in all hooks is important. It’s used because it allows React to check if you are not doing something bad, e.g., call hooks from regular JS functions.
React had its own props checking, before Flow and TypeScript were an option.
PropTypes checks if the properties (props) that are received by a React component and checks if they’re in line with what we have. Whenever a different situation occurs (e.g., object instead of an array), we will get a warning in the console. It is important to note that PropTypes are only checked in development mode due to their impact on performance and the aforementioned console warning.
As of React 15.5, PropTypes are in a different package that needs to be installed separately. They are declared along properties in a static property called propTypes (surprise), combining them with defaultProps which are used if the properties are undefined (undefined is the only case). DefaultProps are not related to PropTypes, but they can solve some warnings that might appear due to PropTypes.
The other two options are Flow and TypeScript, and they are way more popular nowadays (especially TypeScript).
Personally, I find TypeScript faster (practically instantaneous), especially in autocomplete, which seems a bit slower with Flow. It’s worth noting that IDEs such as WebStorm, which I personally use, employ a CLI for integration with Flow. However, it seems even easier to integrate optional use in files, where you simply add // @flow at the beginning of the file to start type checking. Also, from what I can tell, it seems that TypeScript won the battle versus Flow in the end—it is way more popular now, and some of the most popular libraries are getting refactored from Flow to TypeScript.
There are a few more options, mentioned also in official documentation, such as Reason (developed by Facebook and gaining popularity in the React community), Kotlin (a language developed by JetBrains) and more.
Obviously, for front-end developers, the easiest approach would be to hop in and start using Flow and TypeScript, rather than switch to Kotlin or F#. However, for back-end developers that are transitioning to front-end, these might actually be easier to get started with.
The most basic and obvious change that you need to do for production mode is to switch to “production” for DefinePlugin and add UglifyJsPlugin in the case of Webpack. In the case of CRA, it is as simple as using npm run build (which will be running react-scripts build). Be aware that Webpack and CRA are not the only options, as you can use other build tools like Brunch. This is usually covered in official documentation, be it official React documentation or documentation for a specific tool. To make sure that the mode is set correctly, you can use React Developer Tools, which will give you an indication of what kind of build you are using (production vs. development). The aforementioned steps will make your application run without checks and warnings that come from React and the bundle itself will be minimized, too.
There are a few more things you can do for your React app. What do you do with the JS file that is built? You can start with just “bundle.js” if the size is relatively small, or maybe do something like “vendor + bundle” or maybe “vendor + smallest required part + import things when they are needed.” This is useful when you are dealing with a very big app and you do not need to import everything at the very beginning. Be aware that bundling some JavaScript code in the main bundle that is not even being used will simply increase the bundle size and make the app load slower at the very beginning.
Vendor bundles can be useful if you are planning on freezing libraries’ versions upon realizing they might not change for a long time (if ever). Also, bigger files are better at gzipping so the benefit that you get from separating might sometimes not be worth it. It depends on the file size and sometimes you will simply need to try it yourself.
Code splitting can appear in more ways than suggested here, but let’s focus on what we have available in CRA and React itself. Basically, in order to split code into different chunks, we can use import() which works thanks to Webpack (import itself is a proposal in Stage 3 as of now, so it is not part of the language standard just yet). Whenever Webpack sees import, it will know that it needs to start code splitting at this stage and cannot include it in the main bundle (the code that it is inside the import).
Now we can connect it with React.lazy() which requires import() with a file path containing the component that needs to be rendered in that place. Next, we can use React.suspense() which will display a different component in that place until the imported component is loaded. One might wonder; if we are importing a single component, then why we would need it?
That’s not quite the case, as React.lazy() will be showing the component we import(), but import() might fetch a bigger chunk than that single component. For example, that particular component might have other libraries in tow, more code, etc., so one file isn’t necessary—it might be many more files bundled together. Finally, we can wrap all of that in ErrorBoundary (you can find the code in our section on error boundaries) which will serve as a fallback if something fails with the component we wanted to import (e.g., if there’s a network error).
import ErrorBoundary from './ErrorBoundary'; const ComponentOne = React.lazy(() => import('./ComponentOne')); function MyComponent() { return ( <ErrorBoundary> <React.Suspense fallback={ <div>Loading...</div> }> <ComponentOne/> </React.Suspense> </ErrorBoundary> ); }
This is a basic example, but you can obviously do more. You can use import and React.lazy for dynamic route splitting (e.g., admin vs. regular user, or just really big paths that bring a lot). Be aware that React. lazy only supports default exports as of now and doesn’t support server-side rendering.
Regarding performance, if your React application is acting laggy, there are two tools that can help you figure out the issue.
The first one is Chrome Performance Tab, which will tell you what happens with each component (e.g., mount, update). Thanks to that, you should be able to identify which component is exhibiting performance issues trouble and then optimize it.
The other option is to use DevTools Profiler which became available in React 16.5+, and with cooperation from shouldComponentUpdate (or PureComponent, which was explained in part one of this tutorial), we can improve performance for some critical components.
Obviously, employing basic best practices for the web is optimal, such as debouncing some events (e.g., scroll), being cautious with animations (using transform instead of changing the height and animating it) and so on. Using best practices can be overlooked very easily, especially if you are just getting to grips with React.
For more Information and to build a website 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 your custom website using React JS, please visit our technology page.
Content Source:
React components are small, reusable pieces of code that return a React element to be rendered to the page. The simplest version of the React component is a plain JavaScript function that returns a React element. Components can be broken down into distinct pieces of functionality and used within other components. Components can return other components, arrays, strings, and numbers. A good rule of thumb is that if a part of your UI is used several times (Button, Panel, Avatar), or is complex enough on its own (App, FeedStory, Comment), it is a good candidate to be a reusable component.
In most applications, there is a need for input and some form of interaction with users, allowing them to type something, upload a file, select a field, and so on. React deals with user interaction it in two distinct ways – controlled and uncontrolled components.
The value of controlled components, as their name suggests, is controlled by React by providing a value to the element that interacts with the user, while uncontrolled elements do not get a value property. Thanks to that, we have a single source of truth which happens to be the React state, so there is no mismatch between what we are seeing on the screen and what we currently have in our state. The developer needs to pass a function that will respond to user interaction with a form, which will change its state.
class ControlledInput extends React.Component { state = { value: "" }; onChange = (e) => this.setState({ value: e.target.value }); render() { return ( <input value={this.state.value} onChange={this.onChange} /> ); } }
In uncontrolled React components, we do not care about how the value changes, but if we want to know the exact value, we simply access it through ref.
class UncontrolledInput extends React.Component { input = React.createRef(); getValue = () => { console.log(this.input.current.value); }; render() { return ( <input ref={this.input}/> ); } }
So which should be used when? I would say that controlled components are the way to go in most cases, but there are some exceptions. For example, one case where you need to use uncontrolled components in React is the file type input, as its value is read-only and cannot be programmatically set (user interaction is required). Also, I find controlled components easier to read and easier to work with. Doing validation for controlled components is based on the rerender, the state can be changed, and we can easily indicate that there is something wrong with the input (e.g., format or being empty).
We already mentioned refs, which are a special feature that was available in class components until hooks appeared in 16.8.
Refs can give the developer access to a React component or DOM element (depending on the type where we attach ref) through reference. It is considered a good practice to try to avoid them and use them only in must-have scenarios, as they make the code a bit harder to read and break the top-to-bottom data flow. Yet, there are cases where they are necessary, especially on DOM elements (e.g., changing focus programmatically). When attaching to a React component element, you can freely use methods from within that component that you are referring to. Still, this practice should be avoided as there are better ways to deal with it (e.g., lifting state up and moving functions to parent components).
Refs also have three different ways they can be accomplished:
Finally, there are cases when refs aren’t passed down and times when you want to access a deeper reference element from the current component (e.g., you have a <Button> component that has an inside <input> DOM element and right now you are in a <Row> component, and from the row component you want to have access to input the DOM focus function. That’s where you would use forwardRef).
One case where reference is not being passed down is when there is a higher order component being used on a component—the reason is quite understandable as ref is NOT a prop (similar to key) so it isn’t being passed down so it will be referencing the HOC instead of the component being wrapped by it. In such a case, we can use React.forwardRef which takes props and refs as arguments, which can be then assigned to prop and passed down to the component that we want to access.
function withNewReference(Component) { class Hoc extends React.Component { render() { const {forwardedRef, ...props} = this.props; return <Component ref={forwardedRef} {...props}/>; } } return React.forwardRef((props, ref) => { return <Hoc {...props} forwardedRef={ref} />; }); }
The more complex things get, the higher the probability that something will go wrong. That’s why error boundaries are a part of React. So how do they work?
If something goes wrong and there’s no error boundary as its parent, it will result in the whole React app failing. It is better to not display information rather than mislead users and display wrong information, but it doesn’t necessarily mean that you should crash the whole application and show a white screen. With error boundaries, you have an added degree of flexibility that you can use. You can either use one across the whole app and display an error message, or use it in some widgets and simply not display them, or display a small amount of information in place of those widgets instead.
Remember that it is only about issues with declarative code rather than imperative code that you write for handling some events or calls. For these, you should still use the regular try/catch approach.
Error boundaries are also a place where you can send information to the Error Logger that you use (in the componentDidCatch lifecycle method).
class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, info) { logToErrorLogger(error, info); } render() { if (this.state.hasError) { return <div>Help, something went wrong.</div> ; } return this.props.children; } }
Higher Order Components (HOC) are often mentioned in React and are a very popular pattern, one that you will probably use (or already did so). If you’re familiar with HOCs, you’ve probably seen withNavigation, connect, withRouter in many libraries.
HOCs are just functions that take a component as an argument and will return a new component with extended capabilities compared to the one without the HOC wrapper. Thanks to that, you can achieve some easily extensible functions that could enhance your components (e.g., access to navigation). HOCs can also take a few forms called depending on what we have, the only argument always required being a component, but it can take extra arguments—some options, or like in connect, you first invoke a function with configurations that later returns a function which takes an argument component and returns HOC.
There are a few things that you could add and should avoid:
export function importantHoc() { return (Component) => class extends React.Component { importantFunction = () => { console.log("Very Important Function"); }; render() { return ( <Component {...this.props} importantFunction={this.importantFunction} /> ); } }; }
Styling is not necessarily related to React itself but it is worth mentioning for a number of reasons.
First of all, the regular CSS/inline styles apply here as normal and you can simply add class names from CSS in the className attribute, and it will work correctly. The inline styling is a bit different than the regular HTML styling. The string is not being passed down with styles but rather objects with correct values for each. Style attributes are also camelCased, so border-radius becomes borderRadius and so on.
React seems to have popularized a few solutions that became commonplace not only in React, such as CSS modules that were recently integrated within CRA, where you can simply import name.modules.css and use its classes like properties to style your component (some IDEs, e.g., WebStorm, also have Autocomplete for that, which tells you what names are available).
Another solution that is also popular in React is CSS-in-JS (e.g., the emotion library). Just to point out again, CSS modules and emotion (or CSS-in-JS in general) are not limited to React.
Stay tuned to get upcoming react js blog on React Hook and Performance.
For more Information and to build a website 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 your custom website using React JS, please visit our technology page.
Content Source:
The popularity of React seems to be ever growing. React is leading in popularity in Stack overflow’s 2017 most loved component libraries.
React’s virtual DOM, the ability to declaratively describe a user interface and model the state of that interface, low barriers to entry for a decent JavaScript developer, all make React a great go-to library for building UI’s.
Another great reason for working with React is components. Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. To help kickstart your work with React components, here are 10 great React component libraries you should consider for your next app.
Many of these libraries can also be combined with Bit, which enables you to isolate and manage components in any SCM repository, share them to a Scope to make components individually available to discover and install, and keep them synced between different repositories and projects.
React Material-UI is a set of React components that implements Google’s Material Design. With over 30k stars on GitHub, it is probably the most popular React component library. The library’s v1 is coming up.
React-Bootstrap is a reusbale React component library with the look-and-feel of Twitter’s popular Bootstrap. At over 11k stars, its simplicity receives wide popularity in the community.
React Toolbox is a set of React components that implements Google Material Design specification. It’s built on top of some the trendiest proposals like CSS Modules (written in SASS), Webpack and ES6. The library’s website provides a live component playground.
React Belle is a set of React components optimized to work both on mobile & desktop devices. The styles are highly customizable so you can configure the base styles of all the components as well as modify each one of them individually. Here is also a nice example.
React Grommet provides a rich selection of components grouped by usage classifications, and all components are accessible, cross-browser compatible and support theme customization.
Material Components Web is developed by a core team of engineers and UX designers at Google, and its components enable a reliable development workflow to build beautiful and functional web projects. It has replaced react-mdl (which is now deprecated), already reaching nearly 7k stars.
Following the Ant Design specification, React Ant Design is a React UI library that contains a set of components and demos. It’s written in TypeScript with complete defined types, and provides an NPM+ webpack + dva front-end development workflow.
Semantic UI React is the official Semantic-UI-React integration. With nearly 5k stars and used by Netflix and Amazon, these components provide an interesting and flexible arsenal.
Onsen UI React Components made available with Onsen UI React bindings and provide hybrid mobile apps with React and Onsen UI Framework. With 81 contributors and over 5.6k stars it’s an interesting library to consider.
At nearly 8k stars, React Virtualized provides React components for efficiently rendering large lists and tabular data.
Individual components can be found in the popular awesome-react and awesome-react-components projects. Different components can also be grouped into a Scope on the Bit community hub to install and sync components between different repos and projects.
For more information and to build your web app. Hire React.js Developer from us, as we give you 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 app 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