Seb
Seb

Reputation: 3215

How to properly extract params from a URL in react

I have created a webpage to display a profile. By default, the profile page load the user information but I can also load information from another user if I call the profile page with the associated user id.

the URL is /profile or can be /profile?id=12334

In my code, I have simply did this to add the id in the URL when the button is clicked:

<a href="/profile?id=123123">

my profile page for now is just rendering fake data but I do not know how to extract the id and check if the id is there and not empty.


import React from 'react';
import './Profile.css';

import UserProfile from '../assets/fake/studentinfo'
import TextContents from '../assets/translations/TextContents';
import Gallery from 'react-grid-gallery';
import DetailReview from '../components/materialdesign/DetailReview';
import {Tabs, Tab}  from 'react-bootstrap';
import EmptyTile from '../components/EmptyTile';


class Profiles extends React.Component{

    constructor(props, context) {
        super(props);
        this.state = {isUserAccount: true, userId: '', userInfo: UserProfile.User1.values};
    }

    componentDidMount() {
        let { id } = useParams();
        if((id!==null) && (id !== '')) {
            this.setState({userId: id})
            this.setState({isUserAccount: false})
            this.fetchData(id);
        }
    }

    fetchData = id => {
        this.setState({userInfo: UserProfile.User2.values})
    };


    render(){
        

        const IMAGES =
        [{
                src: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_b.jpg",
                thumbnail: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_n.jpg",
                thumbnailWidth: 156,
                thumbnailHeight: 156
        },
        {
                src: "https://c2.staticflickr.com/9/8356/28897120681_3b2c0f43e0_b.jpg",
                thumbnail: "https://c2.staticflickr.com/9/8356/28897120681_3b2c0f43e0_n.jpg",
                thumbnailWidth: 156,
                thumbnailHeight: 156
        },
        
        {
                src: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_b.jpg",
                thumbnail: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_n.jpg",
                thumbnailWidth: 156,
                thumbnailHeight: 156
        },
        {
            src: "https://c2.staticflickr.com/9/8356/28897120681_3b2c0f43e0_b.jpg",
            thumbnail: "https://c2.staticflickr.com/9/8356/28897120681_3b2c0f43e0_n.jpg",
            thumbnailWidth: 156,
            thumbnailHeight: 156
        }]

        return(
            <div className="profile-container">
                <div className="profile-header" 
                    style={{ backgroundImage: `url(${UserProfile.User1.values.profileHeaderImag})`}}>
                        <img 
                        src={UserProfile.User1.values.profileImg} 
                        alt="profileImg"
                        className="profile-header-image-user"/>                    
                </div>
                <div className="profile-content">
                    <h1> {UserProfile.User1.values.name} </h1>
                    <h3> {UserProfile.User1.values.city}  </h3>
                    <h2> {TextContents.Biography} </h2>
                    <p> {UserProfile.User1.values.bio}  </p>
                    <h2> {TextContents.PhotosVideos} </h2>
                    <div className="profile-gallery">
                        <Gallery id="ReactGridGallery" images={IMAGES}/>
                    </div>
                </div>
                <div className="profile-tabs">
                    <Tabs defaultActiveKey="profile" id="uncontrolled-tab-example">
                        <Tab eventKey="yourclasses" title="Your Classes">
                            <div>
                            <EmptyTile text={TextContents.CreateYourOwnClass} url="/createaclass"/>
                            </div>
                        </Tab>
                        <Tab eventKey="joinedclasses" title="Joined Classes">
                        <div>
                            <EmptyTile text={TextContents.DiscoverANewExp} url="/createaclass"/>
                        </div>
                        </Tab>
                        <Tab eventKey="bookmarks" title="Bookmarks">
                        <p> {TextContents.NoBookMarkYet} </p>
                        </Tab>
                        <Tab eventKey="yourhosting" title="Your Hosting">
                        <div>
                            <EmptyTile text={TextContents.HaveBusinessOrHome} url="/createahost"/>
                        </div>
                        </Tab>
                    </Tabs>
                </div>
                <div className="profile-content">
                    <h2>{TextContents.Reviews}</h2>
                        {
                            UserProfile.User1.values.reviews.map((review_item, i) => {
                                return (<DetailReview data={review_item} />);
                            })
                        }
                </div>
            </div>
        )
    }   
}

export default Profiles;

the data will be replaced by the proper one later but for now, I just want to make sure I can easily extract the id if it's there from the URL

Thanks

Upvotes: 0

Views: 671

Answers (2)

Petrogad
Petrogad

Reputation: 4423

If you are using react-router-dom You can use some of their hooks to deconstruct things out of the url.

In this case the hook you're looking for is useParams

const { id } = useParams();

If you're using a class component; you can use the higher order component withRouter or you could use matchPath if you have the path you're matching ahead of time.

Upvotes: 2

Andrea Giammarchi
Andrea Giammarchi

Reputation: 3198

URL and URLSearchParams are what you are after, it doesn't need React, it's native JS. link.searchParams.get('id') would be enough, but it depends on your target browsers, so you might need a polyfill in your code, otherwise:

const {searchParams} = new URL(a.href);
if (searchParams.has('id')) {
  // do your thing with ...
  console.log(searchParams.get('id'));
}

Upvotes: 1

Related Questions