Reputation: 484
I'm not sure if the question title is correct for what I'm trying to do. I've done this before but using the index value to access the data but I'm wondering if I can access my data via the id of my project.
I have this react component that dynamically renders images to the page. Works great and all. But when I click on the image I want to be taken to the correct page (which it does). I'm having trouble accessing the data from my store.
const ClickableImage = ({projects}) => {
const mappedData = projects && projects.map((project, index) => {
return (
<Link to={'/project/' + project.projectId} key={index}>
<img src={project.banner} alt="img" className="clickImage"/>
</Link>
);
})
return (
mappedData
);
}
class LayoutImage extends React.Component {
render() {
const {project} = this.props;
return (
<section className="max-container">
</section>
);
}
}
const mapStateToProps = (state, ownProps) => {
const index = const index = ownProps.match.params.id; //this gives me 1058488271 (the below project id)
const projects = state.projects.projects;
const project = projects ? projects[index] : null;
return {
project: project
}
}
export default connect(mapStateToProps,null)(LayoutImage);
I know I can just pass the index in the link and then get it using const index = ownProps.match.params.id;
to get the value and then just access the index of the array of data that way. But I'm wondering if I can access the data by getting the link key that I passed earlier because I want to retain my link like this http://localhost:8080/project/1058488271
rather than http://localhost:8080/project/0
[
{
banner: "https://somlink/267521129.png"
date: "2021-02-17T20:33:21.822Z"
description: "Lorem Ipsum..."
files: Array(6) [ ]
layout: 1
projectId: 1058488271
tDFiles: ""
title: "Test Project"
},
{},
{},
...
]
Preferably would like an elegant solution without using a loop. Otherwise I can just change my code to
<Link to={'/project/' + index} key={index}>
<img src={project.banner} alt="img" className="clickImage"/>
</Link>
and my problem would be solved. Just don't like how the link will look after
Upvotes: 0
Views: 26
Reputation: 1082
In your mapStateToProps
function, you need to iterate through the projects
to find the project.
Instead of const project = projects ? projects[index] : null;
, you'll do the following:
const project = projects.find(item => item.projectId === index);
Also, index
is probably going to be confusing, you should refer to it as id
or projectId
Upvotes: 1