Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
React infinite/max-level comment for each news post

I have a News feature where user can post their status. However, so far, I cannot make it display all comments of the news as my current solution only allows two-level only. Here are my codes:

News.js (for all)

function News() {

    const {userId, setUserId} = useContext(UserContext);
    const {type, isUserType} = useContext(UserTypeContext);

    const [newsList, setNewsList] = useState([]);

    const rootNews = newsList.filter(
        (newList) => newList.reply_of === null
    );

    const getReplies = commentId => {
        return newsList.filter(newList => newList.reply_of === commentId);
    }


    useEffect(()=>{
        
        Axios.get('http://localhost:3001/news',{  
        })
        .then((response) => {
            if(response.data.length > 0){

                setNewsList(response.data);
            
            }

        })

    },[]);

return (
    <div className = "news p-5">
        <h3 className="news-title">News</h3>
        <div className = "comments-container">
            {rootNews.map((rootNew) => (
                <div>
                    <Comment key={rootNew.news_id} 
                    comment={rootNew}
                    replies={getReplies(rootNew.news_id)}/>
                </div>
            ))}
        </div>
</div>
 )
}

Comment.js (for rendering the comments and replies)

function Comment({comment, replies}) {
  return (
    <div className="comment">
        <div className="comment-image-container">
            <img src = "/user-icon.png" />
        </div>
        <div className="comment-right-part">
            <div className="comment-content">
                <div className="comment-author">
                    {comment.user_name}
                </div>
                <div>{comment.day}, {moment(comment.date).format('DD-MM-YYYY')} at {comment.time}</div>
            </div>
            <div className="comment-text">{comment.news_title}</div>
            {replies.length > 0 && (
                <div className="replies">
                    {replies.map(reply => (
                        <Comment comment={reply} key={reply.news_id} replies={[]}/>
                    ))}
                </div>
            )}
        </div>
    </div>
  )
}

This is an example on how the comment structure would look like:

Comment 1
 Reply 1.1
  Reply 1.1.1
   Reply 1.1.1.1
 Reply 1.2
Comment 2

An idea on how I could render infinite replies, or possibly set the maximum level of replies allowed? Thank you

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

You just need a little change to the Comment component to recursively render the already nested data structure:

function Comment({ comment, newsList }) {
  
  const replies = newsList.filter((newList) => newList.reply_of === comment.news_id);

  return (
    <div className="comment">
      <div className="comment-image-container">
        <img src="/user-icon.png" />
      </div>
      <div className="comment-right-part">
        <div className="comment-content">
          <div className="comment-author">{comment.user_name}</div>
          <div>
            {comment.day}, {moment(comment.date).format("DD-MM-YYYY")} at{" "}
            {comment.time}
          </div>
        </div>
        <div className="comment-text">{comment.news_title}</div>
        {replies.length > 0 && (
          <div className="replies">
            {replies.map((reply) => (
              <Comment key={reply.news_id} comment={reply} newsList={newsList} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

Basically, you just move the code that gets the direct replies to a comment into the Comment component.

When you render the root Comment component, all direct replies to the root comment will be identified and will cause the rendering of nested Comment components, which will in turn identify the replies to the reply, render a nested Comment component and so on.

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda