Comment, Comments (2)

김종민·2022년 5월 8일
0

insta-reactJS

목록 보기
19/27

들어가기
(1)에서 server에서 seeFeed로 Photo를 return받을떄,
Photo에 comments, commentNumber도 같이 return 받을 수 있게,
server에서 설정하고 Home.js에서 seeFeed가 실행될 때,
comments, commentNumber를 받아와 Photo.js에 props로 넘겨 주는것 까지 완료함.


comment component는 전체 댓글을 보여주는 comments component와 댓글 하나를 표현하는 comment component 2개로 나눔
.

1. Photo.js

Home.js에서 받은 comments, commentNumber props를
Comments component에 넘겨줌// * 별표만 확인할 것

const Photo = ({
  id,
  user,
  file,
  isLiked,
  likes,
  caption,
  commentNumber,*****************
  comments,*************
}) => {
  const updateToggleLike = (cache, result) => {
    const {
      data: {
        toggleLike: { ok },
      },
    } = result
    if (ok) {
      const fragmentId = `Photo:${id}`
      const fragment = gql`
        fragment BSName on Photo {
          isLiked
          likes
        }
      `
      const result = cache.readFragment({
        id: fragmentId,
        fragment,
      })
      if ('isLiked' in result && 'likes' in result) {
        const { isLiked: cacheIsLiked, likes: cacheLikes } = result
        cache.writeFragment({
          id: fragmentId,
          fragment,
          data: {
            isLiked: !cacheIsLiked,
            likes: cacheIsLiked ? cacheLikes - 1 : cacheLikes + 1,
          },
        })
      }
    }
  }

  const [toggleLike, { loading }] = useMutation(TOGGLE_LIKE_MUTATION, {
    variables: {
      id,
    },
    update: updateToggleLike,
    // refetchQueries: [{ query: FEED_QUERY }],
  })
  return (
    <div>
      <PhotoContainer key={id}>
        <PhotoHeader>
          <Avatar lg url={user.avatar} />
          <Username>{user.username}</Username>
        </PhotoHeader>
        <PhotoFile src={file} />
        <PhotoData>
          <PhotoActions>
            <div>
              <PhotoAction onClick={toggleLike}>
                <FontAwesomeIcon
                  style={{ color: isLiked ? 'tomato' : 'inherit' }}
                  size={'2x'}
                  icon={isLiked ? SolidHeart : faHeart}
                />
              </PhotoAction>
              <PhotoAction>
                <FontAwesomeIcon size={'2x'} icon={faComment} />
              </PhotoAction>
              <PhotoAction>
                <FontAwesomeIcon size={'2x'} icon={faPaperPlane} />
              </PhotoAction>
            </div>
            <div style={{ marginRight: '15px' }}>
              <FontAwesomeIcon size={'2x'} icon={faBookmark} />
            </div>
          </PhotoActions>
          <Likes>{likes === 1 ? '1 likes' : `${likes} likes`}</Likes>
		******************************************
          <Comments
            author={user.username}
            caption={caption}
            commentNumber={commentNumber}
            comments={comments}
          />
          ****************************************************
        </PhotoData>
      </PhotoContainer>
    </div>
  )
}
export default Photo

2. src/components/feed/Comments.js

Photo.js 에서 comments, commentNumber, author, caption을 props로 받았음.


import styled from "styled-components";
import Comment from "./Comment";

const CommentsContainer = styled.div`
  margin-top: 20px;
`;
const CommentCount = styled.span`
  opacity: 0.7;
  margin: 10px 0px;
  display: block;
  font-weight: 600;
  font-size: 15px;
`;

function Comments({ author, caption, commentNumber, comments }) {
  return (
    <CommentsContainer>
      <Comment author={author} payload={caption} />
      ///사진주인과 사진설명을 나타내는 부분임.
      ///댓글과 햇갈리지 말것.
      
      <CommentCount>
        {commentNumber === 1 ? "1 comment" : `${commentNumber} comments`}
      </CommentCount>
      {comments?.map((comment) => (
        <Comment
          key={comment.id}
          author={comment.user.username}
          payload={comment.payload}
        />
        ///comment component에 각각 commnet의 username과
        ///댓글내용(payload)을 보내줌,
        ///댓글들은 많기 떄문에  map으로 뿌려줌.
        
      ))}
    </CommentsContainer>
  );
}

export default Comments;~~~~

3. src/components/feed/Comment.js

comment부분은 설명할 게 좀 있음.
집중.
1. payload로 받은 부분을 hastag(#orange)로 만들어진
부분이 클릭이 되게 하여서, hastag된 사진들만 모와서
볼 수 있게 만들어준(Link를 걸어줌)

  1. 그렇게 하기 위해서는 hashtag된 부분을 분리시켜주어서
    "#"들어간 부분과 "#"이 안들어간 부분을 true, false로 구분되게
    만들어 주어야 함.

  2. React.Fragment는 <> </> 이렇게만 하면 map에서 key={index}를
    넣을 수가 없기 떄문에 key를 넣을려면, <React.Fragment>로 열고
    </React.Fragment>로 닫아 주어야 함.
    React.Fragment를 사용할려면 import React from 'react'를 해줘야 함.

import styled from 'styled-components'
import { FatText } from '../shared'
import sanitizeHtml from 'sanitize-html'
import React from 'react'
import { Link } from 'react-router-dom'

const CommentContainer = styled.div``
const CommentCaption = styled.span`
  margin-left: 10px;
  a {
    background-color: inherit;
    color: ${(props) => props.theme.accent};
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
    ///1. hashtag되는 부분은 a{ }로 디자인 해줌.
    ///hover가 쓰이는 문법 확인할 것.
    
  }
`
///Comments component에서 author와 payload를 props로 받음.
function Comment({ author, payload }) {
  // const cleanedPayload = sanitizeHtml(
  //   payload.replace(/#[\w]+/g, '<mark>$&</mark>'),
  //   {
  //     allowedTags: ['a'],
  //   }
  // )
------------->sanitizeHtml 사용 예시, 여기서는 사용하지않음.
------------->payload에 html을 입히는 방법
------------->allowedTags는 허용되는 tag만 기입함.
  return (
    <CommentContainer>
      <FatText>{author}</FatText>
      {/* <CommentCaption
        dangerouslySetInnerHTML={{
          __html: cleanedPayload,
        }}
      /> */}
      <CommentCaption>
        {payload.split(" ").map((word, index) =>
          /#[\w]+/.test(word) ? (
            <React.Fragment key={index}>
              <Link to={`/hashtags/${word}`}>{word}</Link>{" "}
            </React.Fragment>
          ) : (
            <React.Fragment key={index}>{word} </React.Fragment>
          )
        )}
      </CommentCaption>
      ///payload(captios, 댓글)을 받아와서, hashtag로 만들어서
      /// hashtag면 Link를 걸어서 `/hashtags/${word}`로
      ///page를 이동시켜 줌.
      ///각각의 단어에 index를 해 주기 위해서 React.Fragment를
      ///사용함.
      
    </CommentContainer>
  )
}

export default Comment
profile
코딩하는초딩쌤

22개의 댓글

comment-user-thumbnail
2023년 1월 3일

Our VIP goa escorts are too appealing models who are seeking for those kinds of men who need sexual joy in their life.https://www.callgirlsstreet.com/escorts/goa They are a wonderful curvy female who is fit to make your evenings noteworthy for a lifetime.

답글 달기
comment-user-thumbnail
2023년 1월 6일

Hello I'm Ankita Oberoi Give You http://www.escortsinindirapuram.com Relationship to Partake in a central improvement with Me and Make two or three Critical times.

답글 달기
comment-user-thumbnail
2023년 2월 1일

We provide the most number of customers in this region, which means you will never be let down when it comes to experiencing what you’ve been promised! To ensure that your privacy is never compromised, we train our Goa escorts on how they should take care of it
https://www.nishamumbaiescorts.in/delhi-escorts.html
https://www.chandigarhescortservice.net/location/delhi-call-girls.html
https://www.jasleenkour.com/delhi-escorts.html
https://www.7stargoaescorts.com/location/delhi-escorts.html
https://www.kolkataescorts69.org.in/locations/call-girls-in-delhi.html

답글 달기
comment-user-thumbnail
2023년 2월 21일

Contributing energy with https://www.delhiqueen.in/goa-call-girls.html can be overwhelming and frustrating, dependent upon what choice you make while finding or wheeling and dealing with your picked Goa Escort young woman.

답글 달기
comment-user-thumbnail
2023년 2월 25일

Our Gurgaon Escorts administration offers real and high profile call young ladies. Book any Gurgaon female https://www.sanakhan.in/gurgaon-call-girls.html escorts administrations from Gurgaon accompanies office for enticing you.

답글 달기
comment-user-thumbnail
2023년 2월 25일

This site enjoys bunches of benefits. I tracked down many fascinating things on this site. Need to deliver https://www.bhopalescorts.net.in some pressure then, at that point, book call young ladies from the given connections.

답글 달기
comment-user-thumbnail
2023년 3월 3일

I'm Ruhi and I'm managing the Delhi Escorts Organization near Entryway of Indian Lodgings, Consistently the clients interest for the free transport of the females who are working in my association.
http://forum.anomalythegame.com/viewtopic.php?f=8&t=76437&sid=86b247bab47bbc6d1a90214d9d3bf209
https://forum.wfz.uw.edu.pl/viewtopic.php?f=17&t=878967#preview
https://forum.resmihat.kz/viewtopic.php?f=2&t=859574
https://eternalys.level52.com/t315-Delhi-Escorts-Service.htm#p613
http://forum.analysisclub.ru/index.php/topic,60239.new.html#new
http://www.organesh.com/se/groups/topic/view/group_id/2987/topic_id/10873/post_id/53708
https://paintball.lv/modules/phpbb/viewtopic.php?f=8&t=909975
https://peneyforum.soforums.com/t57437-Delhi-Escorts-Service.htm#p122197
https://shgs.ru/forum/viewtopic.php?p=1550479#1550479
https://developers.oxwall.com/forum/topic/75331
http://www.shop.minecraftcommand.science/forum/discussions/topics/delhi-escorts-service-vip-call-girls-in-delhi
http://rulesofsurvival.neteasegamer.com/forum.php?mod=viewthread&tid=1244012&extra=
https://denniss.forum2go.nl/viewtopic.php?f=2&t=75318
https://www.ticklingforum.com/showthread.php?349529-Delhi-Escorts-Service&p=4805536#post4805536
https://game.uwants.com/viewthread.php?tid=20424811&extra=&frombbs=1
http://www.wmhelp.cz/html/modules.php?name=Forums&file=viewtopic&p=54514#54514
https://vendors.mikolo.com/forums/discussion/introductions/delhi-escorts-service-call-girls-in-delhi
https://forum.emtb.pl/usercp.php?action=drafts
https://forum.amzgame.com/user/myThreads
http://157.230.37.164/viewtopic.php?f=11&t=157238&sid=73fa8bbd5e37a932b989cd4a2a242548
https://forum.cryptocurrency.tech/topic/645085-delhi-escorts-service/
https://afinsa.forogratis.es/delhi-escorts-service-t19653.html
https://fakethebitch.com/delhi-escorts-service-t73222.html

답글 달기
comment-user-thumbnail
2023년 4월 5일

Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post with people build now woodoku

답글 달기
comment-user-thumbnail
2023년 6월 15일

You should choose a truthful https://www.julieoberoi.com/pune-call-girls/ sensibly in . Because many unscrupulous fake escort agencies are actively online to plunder your hard-earned money for free. They are also supported by some small-minded cheating call girls.

답글 달기
comment-user-thumbnail
2023년 7월 8일

They need to make just like a family relationship with their customers and outfit complete the process of loosening up and please with their impeccable organizations. Their fantastic perspective and organizations make them novel in the gathering as such getting reputation and achievement among the clients. Thusly, one can without a very remarkable stretch book these call girls in Goa through our online site for completing satisfaction.
https://americanwomenorg.com/lisadsouza
https://www.4yo.us/lisadsouza
https://www.atozed.com/forums/user-4179.html
https://talkitter.com/lisadsouza
https://www.destinythegame.me/lisadsouza
https://paperpage.in/lisadsouza
https://prosface.com/lisadsouza
https://geto.space/lisadsouza
https://git.jatimnet.com/lisasdouza
https://elumine.wisdmlabs.com/members/lisadsouza/profile/
https://founders-nation.com/Profile.aspx?id=34436&name=Lisa%20Dsouza
https://bramaby.com/ls/profile/lisadsouza/
https://careers.cannabizconnection.com/employers/2042987-erotic-service-provider
https://careers.msae.net/employers/2042992-service
https://android-help.ru/forum/user/7163-lisadsouza/
https://club.vexanium.com/user/lisa_dsouza
https://www.funbooo.com/1686899314438193_31454
http://ottawa.pinklink.ca/author/lisadsouza/
https://www.strawbalemarket.com/author/lisadsouza/
https://www.elephantjournal.com/profile/lisadsouzagoa/
https://motion-gallery.net/users/537317
https://prodaman.ru/lisadsouza
https://runtrip.jp/user/410364
https://devfolio.co/@lisadsouzagoa
https://buyerseller.xyz/user/lisadsouza/
https://armorama.com/profile/lisa-dsouza
https://www.faneo.es/users/lisadsouza/
https://globalhealthtrainingcentre.tghn.org/community/members/744846/
https://www.campusacada.com/lisadsouza
https://www.downthunder.com.au/mates/lisadsouza
https://www.fcpablogjobs.com/employers/2049313-erotic-service
https://www.nitrnd.com/lisadsouza
http://forums.visualtext.org/member.php?action=profile&uid=950811
https://cynochat.com/lisadsouza
https://ecuamusica.com/lisasdouza
https://netgork.com/lisadsouza
https://lyfepal.com/lisadsouza
http://jobboard.piasd.org/author/lisadsouza/
http://krachelart.com/UserProfile/tabid/43/UserId/1234607/Default.aspx
http://newdigital-world.com/members/lisadsouza.html
https://bulkwp.com/support-forums/users/lisadsouza/
https://careers.coloradopublichealth.org/employers/2053433-escorts-service
https://decidim.cr-reunion.fr/profiles/lisadsouzagoa/timeline
https://jobs.fsoma.org/employers/2053443-goa-escorts
https://undrtone.com/lisadsouza
http://www.servinord.com/phpBB2/profile.php?mode=viewprofile&u=525089
https://asmetalwork.com.ua/forum/user/profile/97154.page
https://blacksocially.com/lisadsouza
http://casualgamerevolution.com/user/lisadsouzaa
https://eligon.ro/community/profile/lisadsouza/
https://inobee.com/lisadsouza
https://social.studentb.eu/lisadsouza
https://git.fuwafuwa.moe/lisasdouza
https://lifeinsys.com/user/lisadsouzaa
https://offcourse.co/users/profile/lisa-dsouzaa
https://www.trainsim.com/vbts/member.php?680694-lisadsouzaa
https://gettogether.community/profile/56484/
https://www.longisland.com/profile/lisadsouza
https://learn.acloud.guru/profile/lisa-dsouza
https://discover.events.com/profile/lisa-dsouza/3700313/savethedate/
https://www.youmagine.com/lisadsouza/designs
https://my.archdaily.com/us/@lisa-dsouza
https://trabajo.merca20.com/author/lisadsouza/
https://www.avianwaves.com/User-Profile/userId/176322
https://www.chirurgiens-esthetiques-plasticiens.com/membres/lisadsouza/
https://www.pintradingdb.com/forum/member.php?action=profile&uid=75480
https://www.themplsegotist.com/members/lisadsouza/
http://www.nafex.net/member.php?18338-lisadsouza
https://jobs.calgeo.org/employers/2067201-julieobero
https://postgresconf.org/users/lisa-dsouza
https://reptes.dca.cat/profiles/lisadsouzagoa/timeline?locale=en
https://mirsistengefort.steinfort.lu/profiles/lisadsouza/timeline?locale=en
https://www.slideshare.net/LisaDsouza15
http://phabricator.legendsofequestria.com/p/lisadsouzaa/
https://decidim.guissona.cat/profiles/lisadsouzagoa/timeline
https://doodleordie.com/profile/lisadsouza
https://user.linkdata.org/user/Lisa_Dsouza/work
https://www.proarti.fr/account/lisadsouza
http://ttlink.com/lisadsouza
https://www.verkami.com/users/1087739
https://www.atelierdesauteurs.com/author/46651421/lisadsouza
https://www.curioos.com/service
https://careercup.com/user?id=4901399647748096
https://face.gta.world/lisadsouza
https://illust.daysneo.com/illustrator/lidadsouza/
https://www.mapleprimes.com/users/lisadsouza
https://www.marqueze.net/miembros/lisadsouza/profile/classic/
https://conifer.rhizome.org/lisadsouza
https://redehumanizasus.net/usuario/lisa-dsouza-dsouza/
https://guides.co/a/goa-escorts-service
https://cannabis.net/user/136169
https://entre-vos-mains.alsace.eu/profiles/lisadsouza/timeline
https://meidan.seinajoki.fi/profiles/lisadsouza/timeline
https://www.dualmonitorbackgrounds.com/lisadsouza
https://hashnode.com/@lisadsouza
https://notionpress.com/author/893646
https://www.openrec.tv/user/w7pf2dg1eq1bj5nvgwmj/about
https://allauthor.com/profile/lisadsouza/
https://influence.co/lisadsouza
https://decide.pamplona.es/profiles/lisadsouzagoa/timeline
https://forum.codeigniter.com/member.php?action=profile&uid=78812
https://30seconds.com/lisadsouza/
https://coub.com/julieoberoi.com
https://myspace.com/lisadsouza
https://www.metal-archives.com/users/lisadsouza
https://www.gta5-mods.com/users/lisadsouza
https://learningapps.org/user/lisadsouza
https://social.msdn.microsoft.com/Profile/Lisa%20Dsouza
https://www.deviantart.com/lisadsouzaa
https://linktr.ee/lisadsouzaa
https://www.workathomejobsboard.com/employers/2093319-julie-oberoi
https://www.pickmemo.com/lisadsouza
https://www.seereadshare.com/author/lisadsouza/
http://gendou.com/user/lisadsouza
https://www.manystories.com/@lisadsouzagoa
https://reactos.org/forum/memberlist.php?mode=viewprofile&u=85397
https://groover.co/en/band/profile/7.lisa/
https://chillspot1.com/friends/lisadsouzagoa
https://participation.bordeaux-metropole.fr/profil-public/lisadsouzaa
https://ellak.gr/user/lisadsouza/
https://www.intensedebate.com/people/lisadsouzaagoa
http://www.annunciogratis.net/author/julieoberoi
https://lkc.hp.com/member/riyanayar78614418
https://aboutmedicalassistantjobs.com/author/julieoberoi/
https://rnopportunities.com/author/julieoberoi/
https://aboutcasemanagerjobs.com/author/julieoberoi/

답글 달기
comment-user-thumbnail
2023년 7월 14일

Only one out of every odd individual is adequately fortunate to find the perfect assistant for them and along these lines, we at call girls organization in Goa has been specialists in outfitting you the perfect week's end date with whom you can go out for a long time, a long way from all of the hustles of your step by step life.
https://www.kolkataescorts69.org.in/locations/call-girls-in-goa.html
https://www.gurgaonescortsqueen.com/Location/Goa-Escorts.html
https://www.ranchiescort.in/goa-call-girls.html
https://www.bhopalescorts.net.in/goa-escorts.html
https://www.modelescortsindelhi.in/goa-call-girls.html

답글 달기
comment-user-thumbnail
2023년 7월 14일

Is it accurate to say that you are prepared for a night out in Goa with a shocking friend, who will let your heart avoid a beat? On the off chance that your answer is true, at that point let our excellent call girls in Goa invite you with a grin all over as well as with a warm grasp.
https://www.indirapuramescorts.com/goa-call-girls.html
https://www.ghaziabadescorts.in/location/goa-call-girls.html
https://www.aerocityescorts.org/escort-in-goa.html
https://www.shwetamalik.in/goa-call-girls.html
https://www.delhiqueen.in/goa-call-girls.html

답글 달기
comment-user-thumbnail
2023년 7월 14일

Thus, it's smart for you to pick an
https://www.callgirlsstreet.com/escorts/goa
for young women when you genuinely need someone who fathoms your necessities and conveys what satisfies you completely.

답글 달기
comment-user-thumbnail
2023년 7월 15일

https://www.7starPanajiescorts.com/location/panaji-escorts.html are instructed enough to be admirably sorted out and thus with them you won't be depleted adequately. With them, you can value the best an incredible time and besides these youngsters are big-hearted in nature, which will make it straightforward for you to introduce some glow in the midst of your trip conversation.

답글 달기
comment-user-thumbnail
2023년 7월 15일

This is the spot we at office transform into the most beneficial pro community with respect to giving good accomplice to a short period of time. In our postings, we also have a monstrous extent of https://www.lisadsouza.com/panaji-call-girls.html who know the claim to fame of sex especially well and they are your most coherent choice for your downturn.

답글 달기
comment-user-thumbnail
2023년 7월 15일

You can speak with her about anything and if getting comfortable is your lone Panajil, they can be the best choice to run with. These call girls are available for both in call and out https://www.missruby.in/panaji-call-girls.html, where it is conceivable that you can visit her favoured place or can demand that her visit you either at your place or some riddle spot of yours.

답글 달기
comment-user-thumbnail
2023년 7월 15일

Presently, plan your incredible end of the week portal with call girls service in India. It is protected to state that you are orchestrating a week's end trip? It is protected to state that you are planning to go as a business voyager or would you say you are an independent wayfarer in this city? In case yes is the reaction to any of the above requests, by then you should want to meet someone at some point or another of time.
https://www.sanakhan.in/wazirabad-call-girls.html
https://www.sanakhan.in/crossings-republik-call-girls.html
https://www.sanakhan.in/connaught-place-call-girls.html
https://www.sanakhan.in/dasna-call-girls.html
https://www.sanakhan.in/lajpat-nagar-call-girls.html

답글 달기
comment-user-thumbnail
2023년 7월 29일

Once you have selected the girls of your choice please call our operator or mail to arrange the booking. https://www.hotcallgirlsjaipur.in/ On booking time you have to keep your id proof, hotel name and room no and mobile no. Please note that for advance bookings you have to inform before 3 days. Girls delivery are free of cost.

답글 달기