I am still a bit new to react and how it works. I have a projects.js file with a list of objects that look like this:
id: 0,
name: "Placeholder Project 1",
description: "Project description",
image: "./assets/images/placeholder-01.png"
There are 6 objects in this array. I am trying to render only 3 project objects at a time, and then include a button that will “load more” projects later. However, I am having trouble with just the rendering part. My component looks like this:
import React, { Component } from "react";
import NavTab from "./NavTab";
import { Card } from "react-bootstrap";
import { PROJECTS } from "../shared/projects";
function RenderProject({projects, projectsDisplayArray}) {
const tempArray = projectsDisplayArray;
return(
<div className="row">
{
projects.map(project => {
tempArray.indexOf(project) > -1 ? console.log('in array already') : tempArray.push(project)
console.log(tempArray.length)
if (tempArray.length >= 3){
console.log('in the if')
return (
<Card key={project.id}>
<Card.Img variant="top" src={project.image} />
<Card.Body>
<Card.Title>{project.name}</Card.Title>
<Card.Text>
{project.description}
</Card.Text>
</Card.Body>
<button className="btn align-self-center">Go somewhere</button>
</Card>
)
}
else {
return(<div>Else return div</div>)
}
})
}
</div>
)
}
export default class Projects extends Component {
constructor(props){
super(props);
this.state = {
projectsPerScreen: 3,
currentPage: 0,
projects: PROJECTS,
projectsDisplayArray: []
}
}
modifyProjectsDisplayArray = props => {
this.setState({projectsDisplayArray: [...this.state.projectsDisplayArray, props]})
}
render() {
let i = 0;
return(
<React.Fragment>
<NavTab/>
<div className="projects">
<div className="container">
<button type="button" className="btn">Click</button>
<h1>Projects: </h1>
<RenderProject projects={this.state.projects} projectsDisplayArray={this.state.projectsDisplayArray} />
<button type="button" className="btn" onClick={() => console.log(this.state.projectsDisplayArray)}>console log</button>
</div>
</div>
</React.Fragment>
)
}
}
I am very confused on how the return
method for RenderProject
is working. When I begin the mapping process, I want to add each project to an array so I can keep track of how many and what projects are being rendered. When the array length hits three, I want it to stop rendering. But whenever I do this, my line if (tempArray.length <= 3)
behaves in a way I don’t expect it to. With how it is now, it won’t return the <Card>
and will instead return the else <div>
for all 6 objects. But if I change the if statement to be if (tempArray.length >= 3)
it will render all 6 objects inside of the array and no else <div>s
. What should I be doing instead?