Get dynamic id from form tag, and use in function

Viewed 86

I have a dynamic id attribute in my form tag, that i would like to use in a function.

The form tag looks like this: <form id={post.id + "liked"} name="liked">

i would like to use that id (post.id + "liked") in a function, like so:

if (direction == "right") {
      // if swipe right = add to bookmarks list
    // HERE IS WHERE I NEED THE ID'S post.id + "liked";
    // eg: 
      context.postBookmark(document.getElementById(post.id + "liked"));
     
    }

But i get the error that post is not defined

Full component:

import React, {
  useContext,
  useEffect,
  useState,
  useCallback,
  useRef,
} from "react";

// Context
import DbContext from "../../../context/DbContext";

const PostCards = (props) => {
  const [distanceInKm, setDistanceInKm] = useState(0);
  const [posts, setPosts] = useState([]);
  const [user, setUser] = useState([]);
  const context = useContext(DbContext);
  const [loading, setLoading] = useState(false);
  const [currentUser, setCurrentUser] = useState([]);

  const [toggleModal, setToggleModal] = useState(false);
  const handleToggleModal = useCallback(() => {
    setUser(context.getUser());

    setToggleModal(!toggleModal);
  });
  useEffect(() => {
    // if (context.existsUser() == null) {
    //   window.location.href = "/login";
    // }
    context.getPosts().then((r) => setPosts(r));
  }, [context]);

  useEffect(() => {
    setCurrentUser(context.getUser());
  }, [context.existsUser()]);

 

  const onSwipe = (direction) => {
    if (direction == "right") {
      // if swipe right = add to bookmarks list

      // HERE IS WHERE I NEED THE ID'S post.id + "liked";
    // eg: 
      context.postBookmark(document.getElementById(post.id + "liked"));
     
    }

    if (direction == "up") {
      setToggleModal(true);
      console.log(
        "Venter på at sælger acceptere, hvorefter betalingen vil blive overført!!! :-)"
      );
    }
    if (direction == "left") {
      console.log("Moved to notinterested");
    }

    console.log("You swiped: " + direction);
  };

  const onCardLeftScreen = (myIdentifier) => {
    console.log(myIdentifier + " left the screen");
  };


  return (
    <>
      <div>
        {posts?.length > 0 ? (
          <div className="postCards__cardContainer">
            {posts?.map((post) => (
              <div>

                <PostCard
                  className="swipe"
                  key={post.id}
                  preventSwipe={["down"]}
                  onSwipe={onSwipe}
              
                  onCardLeftScreen={() => onCardLeftScreen(post.id)}  
                >
                  <Modal
                    open={toggleModal}
                    handleClose={handleToggleModal}
                    loading={loading}
                  >
                    <img
                      src=""
                      alt="Accept_offer_image"
                    />
                    <h3>Sådan {user.name}</h3>
                    <p>
                      Sælger har modtaget dit bud! Så snart sælger har
                      accepteret, trækker vi pengene fra din konto. Når dit køb
                      er sendt, sender vi pengene videre til sælger!
                    </p>
                  </Modal>
                  <div
                    style={{
                      backgroundImage: `url()`,
                    }}
                    className="card"
                  >
                    <h4 className="distance">60 kilometer</h4>
                    <h4 className="price">{post?.price} kr.</h4>

                    {/* LINK TO ADVERSE */}
                    <Link className="post_title" to={`/showpost/${post.id}`}>
                      {post.title}
                    </Link>
                  </div>

                  {/*  THE ID I WNAT TO USE: id={post.id + "liked"} */}
                  <form id={post.id + "liked"} name="liked" ref={submitTest}>
                    {/* GET THESE */}
                    <input name="postId" id="postId" defaultValue={post.id} />
                    <input
                      name="userId"
                      id="userId"
                      defaultValue={currentUser?.id}
                    />
                    <button hidden type="submit" className="btn btn-primary">
                      LIKE
                    </button>
                  </form>
                </PostCard>
              </div>
            ))}
          </div>
        ) : (
          <Loader
            className="loader"
            type="MutatingDots"
            color="#052131"
            secondaryColor="#909090"
            height={100}
            width={100}
            timeout={3000} //3 secs
          />
        )}
      </div>
      <div className="swipeButtons">
        <IconButton className="swipeButtons__repeat">
          <ReplayIcon fontSize="large" />
        </IconButton>
        <IconButton className="swipeButtons__left">
          <CloseIcon fontSize="large" />
        </IconButton>
        <IconButton className="swipeButtons__star">
          <StarRateIcon fontSize="large" />
        </IconButton>
        <IconButton className="swipeButtons__right">
          <FavoriteIcon fontSize="large" />
        </IconButton>
        <IconButton className="swipeButtons__lightning">
          <FlashOnIcon fontSize="large" />
        </IconButton>
      </div>
    </>
  );
};

export default PostCards;
1 Answers

post can be passed to onSwipe method using bind and then post.id will throw error.

const onSwipe = (post, direction) => { // post will be available }
...

<PostCard
 className="swipe"
 key={post.id}
 preventSwipe={["down"]}
 onSwipe={onSwipe.bind(null, post)} >
 ...
</PostCard>
Related