Alex Alex - 2 months ago 15
React JSX Question

React filter array based on this.props.params.id

I have the following component:

import React from 'react';

import porgectsCollection from './../data/projectInfo.js';

class SingleProject extends React.Component {
getProjectId() {
let projectID = porgectsCollection.filter(el => {
return (el.title = {this.props.params.id});
});
}
render () {
console.log(this.getProjectId);
return (
<div>
<h2>{this.props.params.id}</h2>
</div>
);
}
}

export default SingleProject;


and my routes.jsx as follow:

import React from 'react';
import { Route, Router, IndexRoute } from 'react-router';
import ReactDOM from 'react-dom';

import Wrapper from './../wrapper.jsx';
import Home from './../home.jsx';
import Projects from './../projects.jsx';
import SingleProject from './../singleProject.jsx';

ReactDOM.render((
<Router>
<Route component={Wrapper} >
<Route path="/" component={Home} />
<Route path="projects" component={Projects} />
<Route path="projects/:id" component={SingleProject} />
</Route>
</Router>
), document.getElementById('app'));


Based on the id passed in:

<Route path="projects/:id" component={SingleProject} />


I want to get that value and filter through the array coming from:

import porgectsCollection from './../data/projectInfo.js';


I am then trying to use this function:

getProjectId() {
let projectID = porgectsCollection.filter(el => {
return (el.title = {this.props.params.id});
});
}


to display the correct data.

I am not sure if this is the right approach however I am also getting an error when I run webpack:

unexpected token referring to {this.props.params.id}

Answer

You shouldn't need the brackets - it is just in a normal JS function:

  getProjectId() {
    let projectID = porgectsCollection.filter(el => {
        return el.title === this.props.params.id;
    });
  }

Some shinier formatting:

  getProjectId() {
    return porgectsCollection.filter(el => el.title === this.props.params.id);
  }

(also you made a typo in "projects" but I left it to be consistent)

Comments