0

I am trying to pass down a state into the following route using the ':group'. Is that possible?

Router.js file (parts of it):

   const [ groups, setGroups ] = useState([])

    useEffect( () => {
        const result = () => {
            fetch("http://localhost:5000/groups", {method: "GET"})
                .then(response => response.json())
                .then(data => setGroups(data.groups))
                .catch(err => {
                    console.error(err)
                })
            }
            result()
    }, [])

    return (
       <Route 
           exact 
           path={`/groups/:group`} 
           render={ routeProps => 
              <GroupDetails 
                   routeProps={routeProps} 
          /> } 
       />
    )

GroupDetails page: Just putting the necessary code

const GroupDetails = ({routeProps, userId }) => {

    const [ details, setDetails ] = useState(routeProps.location.state)

Right now, from my groups page, if I click on a specific group, it takes me to the page. But if typed in "www.website.com/groups/groupname" it would be undefined because there's nothing in the routeProp.location.state.

I'm thinking about just setting a groupId state at the top component and doing setGroupId everytime a group page is clicked, and passing that down to the pathname as /groups/${groupId}. I could see this working, but I'm wondering if I can use React Router to do this.

Thanks

chanp.ark
  • 55
  • 1
  • 5

2 Answers2

0

Well, you can use withRouter to get the param :group.

Here is the docs for withRouter: https://reacttraining.com/react-router/web/api/withRouter

Also, here is another question that maybe can help you: React - How to get parameter value from query string

0

Generally location.state is used with history.push. When you are rendering component with , you can send children inside as well.

const [ groups, setGroups ] = useState([])

    useEffect( () => {
        const result = () => {
            fetch("http://localhost:5000/groups", {method: "GET"})
                .then(response => response.json())
                .then(data => setGroups(data.groups))
                .catch(err => {
                    console.error(err)
                })
            }
            result()
    }, [])

    return (
       <Route 
           exact 
           path={`/groups/:group`} 
       >
       <GroupDetails 
           // pass whatever prop
          />
      </Route>
    )

In GroupDetails component, you can use hooks provided by react-router. They might get you what you want.

const GroupDetails = ({routeProps, userId }) => {
    const history = useHistory()
    const {url, path} = useRouteMatch()
    const location = useLocation()
    const parameters = useParams() // :group will be found here
    const [ details, setDetails ] = useState(routeProps.location.state)

Please let me know if I havent understood your question or this didnt solve your problem.

gautamits
  • 1,262
  • 9
  • 11