Rohit Verma
Rohit Verma

Reputation: 3785

How to display data according to query string using ReactJs?

I have multiple data & I want to display data as per query string, how can I do that in reactJs?

My code:

const Ladies = () => {

  return (
      <div>
      if('http://localhost:3000/ladies?service=makeup'){
      <div>Makeup Content</div>
      }
      else('http://localhost:3000/ladies?service=hairStyling'){
      <div>Hair Styling Content</div>
      }      
      </div>
      )
      
}

Thank You!

Upvotes: 2

Views: 53

Answers (1)

Yaya
Yaya

Reputation: 4838

I consider this for your url

http://localhost:3000/ladies?service=makeup

In your code

const params = new URLSearchParams(window.location.search)

check if it has the query

params.has('service')?params.get('service'):""

or log it

console.log(params.has('service')?params.get('service'):"")

return will be makeup

I'm not sure but i think it will be string so if you want to use it check if it's equal to "makeup" like so

<div> {params.has('service')&&params.get('service')==="makeup"?"There is makeup":"There is no make up in query strings !"}</div>

Update:

you can put that just like a text to show a div instead, that is a great feature of jsx, do it like this.

<div>
  {params.has("service") && params.get("service") === "makeup" ? (
    <div>Makeup section</div>
  ) : params.get("service") === "hairStyling" ? (
    <div>hair styling section</div>
  ) : (
    <div>cannot find any query strings</div>
  )}
</div>

For more info check out here

Upvotes: 3

Related Questions