0

I have an array of posts where I would like to use the values from the url or route to determine what I want to show in the array, something like a filter. For example, my selected post is 'www.mywebsite.com/chocolate' so in my route where I display my posts, I only display 'chocolate' and not all the other posts. Is there something I can do like this, where the result === 'chocolate':

const post = response.data.filter(({url}) => url === 'dynamic_variable_that_knows_what_the_current_url_is_with_the_value_of_chocolate');

Below is my code for App.js:

getData() {
    axios.get('/posts.json')
        .then(response => {
            //console.log(response);
            const post = response.data;
            const updatedPosts = post.map(post => {
                return {
                    ...post
                }
            });

            this.setState({
                posts: updatedPosts
            });
        })
        .catch(error => {
            console.log(error);
        });
}

render() {

    return (
        <div className={classes.App}>
            <Layout>
              <Switch>
                <Route path="/food/:slug" exact render={(props) => this.state.posts.map(post => { return (<FullPost key={post.id} id={post.id} pathname="/:slug" {...props} />)} )} />
                <Route render={() => <h1>Whoops! What you're looking for isn't here anymore.</h1>} />
              </Switch>
            </Layout>
        </div>
     );
}

1 Answer 1

2

Use props.match.params to access the slug and filter later.

Consider following example from Router 4 documentation.

<Route path="/user/:username" component={User}/>

const User = ({ match }) => {
  return <h1>Hello {match.params.username}!</h1>
}

In your case it will look similar to

const post = response.data.filter(url => url === this.props.match.params.slug);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the suggestion, it looks like I'm getting a 'Cannot read property 'params' of undefined though...
because you'd have to make sure this references your Component. Be careful how you call getData()
Thank you, I understand what you mean now. To help others I will clarify that because I was doing the filtering logic on the App.js level, there are no components to pass the props params to, I can't directly pass props from App.js to FullPost,js. So I created an intermediary component that filters the posts to which I can access props and pass props. So the flow would be like this. App.js contains the <Route> that loads the intermediary <FullPostSorter> (which has props) that loads the <FullPost> (which pulls in the props from FullPostSorter).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.