yikegaya’s blog

yikegayaのブログ

reactでレビュー機能を実装する

こういう↓星付きのレビュー機能をReactのポートフォリオに実装した時のメモ。

CSSフレームワークbulmaのモーダルで動かしている。

f:id:ikeyu0806720:20200807105827p:plain

const [score, setScore] = useState<number>(3)
const [isShowModal, setIsShowModal] = useState<boolean>(false)

return (
<div className={isShowModal ? "modal is-active" : "modal"}>
<div className="modal-background"></div>
  <div className="modal-card">
    <header className="modal-card-head">
      <p className="modal-card-title">{movie.title}</p>
      <button className="delete" aria-label="close" onClick={closeModal}></button>
    </header>
    <section className="modal-card-body">
    <div className="field">
      <label className="label">感想</label>
      <div className="control">
        <textarea className="textarea" onChange={(e) => { setComment(e.target.value)}}></textarea>
      </div>
    </div>
    <div className="field rate-field columns star">
      <a className={(score >= 1) ? "yellow-star" : "silver-star"} onClick={() => setScore(1)}>★</a>
      <a className={(score >= 2) ? "yellow-star" : "silver-star"} onClick={() => setScore(2)}>★</a>
      <a className={(score >= 3) ? "yellow-star" : "silver-star"} onClick={() => setScore(3)}>★</a>
      <a className={(score >= 4) ? "yellow-star" : "silver-star"} onClick={() => setScore(4)}>★</a>
      <a className={(score >= 5) ? "yellow-star" : "silver-star"} onClick={() => setScore(5)}>★</a>
    </div>
    </section>
    <footer className="modal-card-foot">
      <button className="button is-success" onClick={submitReview}>投稿する</button>
      <button className="button" onClick={closeModal}>キャンセル</button>
    </footer>
  </div>
</div>
)
      <style jsx>{`
        .star {
          position: relative;
          font-size: 30px;
          letter-spacing : 0px;
        }
        .yellow-star {
          color: yellow;
        }
        .silver-star {
          color: silver;
        }
        .comments {
          margin-top: 20px;
        }
        .reviews {
          margin-top: 20px;
        }
        .review-list {
          margin-bottom: 20px;
        }
        .review-comment {
          margin-bottom: 30px;
          margin-left: 10px;
        }
        .reviewed-stars {
          margin-left: 10px;
        }
        .reviewed-star {
          position: relative;
          font-size: 15px;
          letter-spacing : 0px;
        }
      `}</style>

後はaxiosでstateをバックエンドにpostしてDB登録しておく。

  const params: Review = {
    movie_id: movie.id,
    public_id: Math.floor( Math.random() * (999999)),
    comment: comment,
    score: score,
  }

  const submitReview = () => {
    axios.post('http://localhost:3002/review/create', params)
    .then((response) => {
      console.log(response)
      router.push({
        pathname: '/Movie/' + movie.id,
        query: { review: 'success' }
     })
    })
    .catch((error) => {
      console.log(error)
    })
  }