Ethan Hughes

Ethan Hughes

1576176122

How to Pass More Than One Parameter in React

Introduction

Recently, I came across an interesting problem I hadn’t encountered before. I wanted to pass more than one route parameter in a React URL route path, then access those parameters in a component upon redirect.

The reason for this problem arose when I was building a demo project to illustrate various ways to do responsive web design with ReactJS. I was using The Movie Database API to supply movie data to my React front end project.

What I wanted was for a user to see a list of movie genres (action, adventure, comedy, etc.), click on a genre, and be redirected to a list of movies that fell into that genre. Seems straightforward enough, right?

Action

Well, yes, it seems simple…except that the movie API supplying the list of movies based on genre required a genreId to fetch the data, while what I wanted to display to users along with the movie list was the genreName that they’d actually clicked on to generate this list. Do you see my problem?

Two different pieces of data, both required by a different, unrelated component upon redirect (so passing data through props like with a typical child component was out of the question) from the genericGenres component to the specific GenreList component displaying the movies related to that genre.

Surprisingly, when I started to look for examples of how to pass multiple route parameters in a URL path in React, I couldn’t find much.

So that’s what I wanted to share today: How to add, and later access, multiple route parameters in a ReactJS project upon redirect using react-router-dom, the most popular router for React applications.

React Routes and Route Parameters

Before I go much further, let me clarify what routes and route parameters are in ReactJS, in case you’re not familiar.

I’ll be using my demo project repo, so if you’d like to see the complete codebase or the working demo, they’re available here and here.

If you’re completely new to how routing works in ReactJS, I recommend checking out react-router-dom’s documentation first. This will not be an in-depth explanation of that, but it is the router I’m using in this article.

Routes

Routes specify the path to different components in a ReactJS application. When a user clicks a link to a page or hits a button that redirects him/her, the router renders the matching <Route /> for that component. For instance, this is what the route for the Genres page in my movie app looks like.

Traditional, static route URL in React:

React

<Route exact path="/genres" component={Genres} />

This is a static route that will always be the same, regardless of who the user is or which page they’re coming from. No matter what, whenever they click a link to go to the Genres page, this route will always be used to get them there, and it will always render the same component — no dynamic content required.

Route parameters

Route params are parameters whose values are set dynamically in a page’s URL. This allows a route to render the same component while passing that component the dynamic portion of the URL, so that it can change its data based on the parameter.

Examples of URL route params you might recognize include things like IDs for products, books, users, or, in my case, movies. At least with React, in order to get the details for the correct item, the dynamic component would need the unique, specific ID of the item supplied, so it could get the correct data to display.

Here’s what the MovieDetailsContainer route with dynamic URL parameters in my app looks like.

Dynamic route URL in React:

React
This is a dynamic route with placeholders for :id that will be updated on-the-fly based on user input.

<Route exact path="/movie/:id" component={MovieDetailsContainer} />

This is an example of a dynamically updating route. The first part of the path, the "/movie/” part, doesn’t change, but the :id is a route parameter that is set dynamically — usually from a user’s actions, like clicking a link or typing an input and clicking a search button.

This is what changes and it causes the MovieDetailsContainer to be rendered with the ID of the movie included. The component then pulls this out of the URL path when it renders to get the details of that particular movie to show to a user.

Accessing dynamic route params in a component

Typically, the component being rendered on redirect will access the dynamic route info it needs from the URL.

Accessing dynamic path parameter in a URL:

React
This is the object you need to access to reach the URL path in ReactJS.

this.props.match.params.id

Inside a React component that needs URL path data, this is the code you’ll have to use to access the route’s actual ID, which was shown as a placeholder in the route path as :id. It’s a little verbose, I agree, but up until react-router-dom’s React hooks updates, it was what we had to use to access the data.

From there it can be set to local component state, used to fetch data, rendered out in the JSX, etc.

That is pretty much where the online tutorials stop: with a redirect example showing a single :id path param. This is where my piece picks up.

Setting up the new dynamic route path

Hopefully, we’re on the same page now. Routes are clear. Route params are clear. Accessing those parameters from a component that a user is redirected to is clear. The only thing that still remains unclear is what to do if you have more than one dynamic route parameter to add to a route path.

Knowing what I knew about React route paths in react-router-dom, I decided to try creating a route path for the GenreList component. This is the component that shows the list of movies associated with a particular genre using two dynamic parameters: :genreName and :genreId.

Note: All of my actual routing for the app was contained in the App.js file inside the src folder, for clarity.

App.js
React
This is a dynamic route with placeholders for both genreName and genreId as part of the URL.

<Route
  exact
  path="/genres/:genreName/:genreId"
  component={GenreList}
/>

This was step one of handling a route containing more than one route parameter. The next step is setting the genre ID and genre name in the Genres component.

Adding more than one route parameter to a URL

The Genres component contains, among other things, two state objects: selectedGenre (a number initially set to 0) and selectedGenreName (a string initially set to ‘’). These are the two pieces of state which will be set by a user clicking one of the genres listed in the list.

As soon as a user clicks a single genre, the genre’s ID and name are set in the Genres component’s state. This triggers the renderRedirect() function you see below, to redirect the user to the GenresList component, as defined by the route path.

this.state.selectedGenreName is inserted as the route placeholder :genreName .this.state.selectedGenre is replaced with the route placeholder :genreId.

Genres.js

React
Redirect code for including both the genre name and genre ID in the URL.

renderRedirect = () => {
  if (this.state.selectedGenre !== 0 && this.state.selectedGenreName !== '') {
    return (
      <Redirect 
        to={`/genres/${this.state.selectedGenreName}/${this.state.selectedGenre}`}
      />
    );
  }
};

Step two is now complete. A particular genre ID, required by the unrelated GenreList component to fetch movies of that genre is part of the URL, and the genre name, to display which genre the user’s viewing movies for, is also included. Let’s go to the redirect component, GenreList, that now needs this data.

Accessing the route parameters from a URL

OK, last step: the component being redirected to, GenreList, needs to pull out the different pieces of the dynamic React route path. It needs the genreId to fetch the movie list from The Movie Database API, which it extracts with this.props.match.params.genreId, and it needs genreName to display in the component’s JSX , showing which genre the user clicked on, which is accessed via this.props.match.params.genreName.

Pretty cool!

GenreList.js

React
Code for pulling the genreId out of the URL for the data fetching call and the genreName from the URL for the display in the JSX rendered code.

if (this.props.match.params) {
  try {
    const movies = await movieAPI.getMoviesByGenre(
      this.props.match.params.genreId,
    );
    this.setState({ movies, loading: false });
  } catch (err) {
      this.setState({ loading: false, error: true });
    }
  }
}
render() {
  return (
    <>
      <div className="genre-search-title" onClick={() => this.props.history.push('/genres')} >
        <div>
          <i className="fa fa-chevron-left" aria-hidden="true" />
          <p>Back to Genres</p>
        </div>    
        <h1>{this.props.match.params.genreName} Movies</h1>
      </div>
      <MovieList
       loading={this.state.loading}
       error={this.state.error}
       movies={this.state.movies}
      />
    </>
  );
}

I didn’t believe it could be that simple for a redirect, but it was!

Just by using the correct URL path params syntax (this.props.match.params...) and passing the corresponding variable name (genreId or genreName), I was able to pull out the correct value.

This sort of thing can be done anywhere you need dynamic data when redirecting from one unrelated component to another.

Conclusion

Dynamic redirects are a fairly common occurrence in any web application, React apps included, but despite this, tutorials illustrating them are not so easy to come by. And examples of redirects with more than one piece of dynamic data are non-existent, which is why I decided to write a piece about just that.

With the help of react-router-dom’s route paths and dynamic parameters, it really isn’t as complicated as I once thought to pass more than one piece of data from one component to another unrelated component via a redirect.

Check back in a few weeks, I’ll be writing more about JavaScript, React, ES6 or something else related to web development. Follow me so you don’t miss out!

Thanks for reading, I hope I’ve made ReactJS redirects with dynamic URL route params a little clearer and that this was something you’ll find useful in your own applications.

#reactjs #javascript #programming #react

What is GEEK

Buddha Community

How to Pass More Than One Parameter in React
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

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.

A brief introduction to React Native

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:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

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:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

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

What are hooks in React JS? - INFO AT ONE

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

Mathew Rini

1615544450

How to Select and Hire the Best React JS and React Native Developers?

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.

What is React.js?

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.

React vs React Native

  • React Native is a platform that uses a collection of mobile-specific components provided by the React kit, while React.js is a JavaScript-based library.
  • React.js and React Native have similar syntax and workflows, but their implementation is quite different.
  • React Native is designed to create native mobile apps that are distinct from those created in Objective-C or Java. React, on the other hand, can be used to develop web apps, hybrid and mobile & desktop applications.
  • React Native, in essence, takes the same conceptual UI cornerstones as standard iOS and Android apps and assembles them using React.js syntax to create a rich mobile experience.

What is the Average React Developer Salary?

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.

* React.js Developer Salary by Country

  • United States- $120,000
  • Canada - $110,000
  • United Kingdom - $71,820
  • The Netherlands $49,095
  • Spain - $35,423.00
  • France - $44,284
  • Ukraine - $28,990
  • India - $9,843
  • Sweden - $55,173
  • Singapore - $43,801

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.

How to Hire React.js Developers?

  • Conduct thorough candidate research, including portfolios and areas of expertise.
  • Before you sit down with your interviewing panel, do some homework.
  • Examine the final outcome and hire the ideal candidate.

Why is React.js Popular?

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.

Final thoughts:

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

Aria Barnes

Aria Barnes

1627031571

React 18: Things You Need To Know About React JS Latest Version

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 SurveyReact 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.
ReactJS stats.pngSo, 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.

Read more here: React 18: Things You Need To Know About React JS Latest Version

#hire react js developers #hire react js developers india #react developers india #react js developer #react developer #hire react developers

Aubrey  Price

Aubrey Price

1589722410

Build a simple React Native Pokemon app with React-Navigation

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