Home > Net >  when clicking the button, nothing happens in React
when clicking the button, nothing happens in React

Time:11-11

I'm trying to show a cart when clicking button in React. But when the button is clicked, nothing happens.

This is my App.js:

function App() {
  const [cartIsShown, setCartIsShown] = useState(false);

  const showProjectHandler = () => {
    
     setCartIsShown(true);
     console.log('test')
  };

  const hidePojectHandler = () => {
    setCartIsShown(false);
  };
  return (
    <div className="App">
      <NavBar />
      <Banner />
      <Skills />
       {cartIsShown && < ProjectCart onClose={hidePojectHandler}/>} 
      <Projects  onshowProject={showProjectHandler}/>
      <Contact />
      <Footer />
    </div>
  );
}

and this is my code in Projects.js:

<Row>
{projects.map((project, index) => {
  return (
    <ProjectCard
      key={index}
      {...project}
      showProject={props.onshowProject}
    />
  );
})}
</Row>

and this is my code in projectCard.js:

export const ProjectCard = ({ title, description, imgUrl }, props) => {
  return (
    <Col size={12} sm={5} md={4}>
      <div className="proj-imgbx" onClick={props.showProject}>
        <img src={imgUrl} />
        <div className="proj-txtx">
          <h4>{title}</h4>
          <span>{description}</span>
        </div>
      </div>
    </Col>
  );
};

Can anyone help me with what is wrong with my code?

CodePudding user response:

At Projects component => I see you use pure props. If i'm wrong, you please comment properties of Props of Projects to me.

export const Projects = (props) => {
  return (
    <Row>
      {projects.map((project, index) => {
        return (
          <ProjectCard
            key={index}
            {...project}
            showProject={props.onshowProject}
          />
        );
      })}
    </Row>
  );
};

At ProjectCard component => If you're using Destructuring Assignment to declare properties of Props as variables, you should keep declaring showProject variable like this:

export const ProjectCard = ({ title, description, imgUrl, showProject}) => {
  return (
    <Col size={12} sm={5} md={4}>
      <div className="proj-imgbx" onClick={showProject}>
      ...
      </div>
    </Col>
  );
};

Or if you want to combine both Destructuring Assignment and Rest Parameters for Props:

export const ProjectCard = ({ title, description, imgUrl, ...restProp}) => {
  return (
    <Col size={12} sm={5} md={4}>
      <div className="proj-imgbx" onClick={restProp.showProject}>
      ...
      </div>
    </Col>
  );
};
  • Related