Home > Enterprise >  Call component function that inside a page from another page
Call component function that inside a page from another page

Time:05-04

I'm trying to understand how I can trigger OnSwipe from inside another JS file called CardFooter.js containing a button with OnClick triggering OnSwipe from the previous JS file called CardItem.js. They both are called inside Card.js.

I'm learning Nextjs with Reactjs components. Any insight would greatly be appreciated

CardFooter.js

import { CardItem }  from '../components/CardItem'

const CardFooter = () => { 

   return (
   
       <Button onClick={() => CardItem.onSwipe('left')}></Button>;
       <Button onClick={() => CardItem.onSwipe('right')}></Button>;

   )
}

export default CardFooter

CardItem.js

import { useState, useContext, createContext } from 'react'
import { Context } from '../context/Context'
import TinderCard from 'react-tinder-card'
import { test } from '../components/CardFooter';

export const CardItem = ({ card }) => {

  const { handleRightSwipe, handleLeftSwipe, currentAccount } = useContext(Context)

  const onSwipe = dir => {
    if (dir === 'right') {
      handleRightSwipe(card, currentAccount)
    }
    if (dir === 'left') {
      handleLeftSwipe(card, currentAccount)
    }
  } 

  return (
    <TinderCard
      preventSwipe={['up', 'down']}
      onSwipe={onSwipe}
    >
    <div style={{ backgroundImage: `url('${card.imageUrl}')` }}>
    <div>
      {card.name}
    </div>
  </div> 
</TinderCard> 
)
}

export default CardItem

Card.js

import { useContext } from 'react'
import { Context } from '../context/Context'
import CardFooter from './CardFooter'
import CardItem from './CardItem'

const Card = () => {

const { cardsData } = useContext(Context)

  return (
    <div className={style.wrapper}>
      <div className={style.cardMain}>
        <div className={style.swipesContainer}>
          {cardsData.map((card, index) => (
            <CardItem card={card} key={index} />  
          ))}
        </div>
      </div>
      <CardFooter  />
    </div>
  )
}

export default Card

CodePudding user response:

In React, you can't pass props up from child components into parent components. This means that you wouldn't be able to pass the handleSwipe function up to <CardFooter>.

But it doesn't look like you'd need to do that anyways, since you have the handleRightSwipe and handleLeftSwipe functions within your Context, and all the handleSwipe function is really doing is calling those functions.

So, with this in mind, there are two solutions:

  1. In your footer, import the context and use it, then when the user clicks on the right button, call handleRightSwipe, and handleLeftSwipe for the left button. (this is the naive solution)

  2. Define handleSwipe within the parent <Card> component, then pass it as a prop to both of the components. This way, you only need to define the function once. (ideal solution)

  • Related