React로 재미있는 번역 앱 만들기

39750 단어 react



Source Code


Live Preview

뭐야?



이 앱은 사용자의 입력으로 일부 텍스트를 가져온 다음 문자 언어에 따라 번역합니다. 일부 텍스트를 미니언의 언어로 번역하고 싶다고 가정하면
  • 먼저 홈페이지에서 Minion 옵션을 선택해야 합니다
  • .
  • 그런 다음 텍스트 상자 필드에 예상 텍스트를 입력해야 합니다
  • .
  • 그런 다음 양식을 제출해야 합니다. 그러면 예상 문자 언어로 번역됩니다
  • .

    단계


  • 다음을 사용하여 funtranslation이라는 새 반응 앱을 만듭니다.npx create-react-app funtranslation

  • 내비게이션에 react-router-dom 추가

    yarn add react-router-dom or
    npm install react-router-dom


  • BrowserRounter 파일에 index.js 래핑

  • import React from "react";
    import ReactDOM from "react-dom";
    import App from "./App";
    import { BrowserRouter as Router } from "react-router-dom";
    
    ReactDOM.render(
      <Router>
        <React.StrictMode>
          <App />
        </React.StrictMode>
      </Router>,
      document.getElementById("root")
    );
    


  • 다음과 같은 번역기 유형에 대해 6개의 다른 탐색 항목을 만듭니다.
    요다, 미니언, 도트라키, 발리리안, 만달로리얀, 셰익스피어
  • NavBar.jsx
    import NavItem from "./NavItem";
    
    const NavBar = () => {
      return (
        <nav>
          <ul>
            <NavItem path="/yoda" linkName="Yoda" />
            <NavItem path="/minion" linkName="Minion" />
            <NavItem path="/dothraki" linkName="Dothraki" />
            <NavItem path="/valyrian" linkName="Valyrian" />
            <NavItem path="/mandalorian" linkName="Mandalorian" />
            <NavItem path="/shakespeare" linkName="Shakespeare" />
          </ul>
        </nav>
      );
    };
    
    export default NavBar;
    
    

    NavItem.jsx
    import { NavLink } from "react-router-dom";
    const NavItem = ({ path, linkName }) => {
      return <NavLink to={path}>{linkName}</NavLink>;
    };
    
    export default NavItem;
    
    


  • 이제 모든 구성 요소에 대한 경로를 설정합니다.App.jsx

  • import { Route, Switch } from "react-router-dom";
    import Home from "./containers/Home";
    import Yoda from "./containers/Yoda";
    import Minion from "./containers/Minion";
    import Dothraki from "./containers/Dothraki";
    import Valyrian from "./containers/Valyrian";
    import Mandalorian from "./containers/Mandalorian";
    import Shakespeare from "./containers/Shakespeare";
    
    const App = () => {
      return (
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/yoda" exact component={Yoda} />
          <Route path="/minion" exact component={Minion} />
          <Route path="/dothraki" exact component={Dothraki} />
          <Route path="/valyrian" exact component={Valyrian} />
          <Route path="/mandalorian" exact component={Mandalorian} />
          <Route path="/shakespeare" exact component={Shakespeare} />
        </Switch>
      );
    };
    export default App;
    


  • 6개의 서로 다른 구성 요소[ Yoda, Minion, Dothraki, Valyrian, Mandalorian, Shakespeare] 모두에서 사용자 입력 텍스트를 처리할 사용자 정의 후크를 만듭니다.
  • useTranslateText.jsx
    import { useReducer, useState, useEffect } from "react";
    
    const textReducer = (state, action) => {
      switch (action.type) {
        case "ENTER_TEXT":
          return action.payload.text;
        default:
          return state;
      }
    };
    
    export const useTranslateText = (translator) => {
      const [textToTranslate, dispatch] = useReducer(textReducer, "");
      const [translatedContent, setTranslatedContent] = useState({});
    
      useEffect(() => {
        let isActive = true;
        const startTranslation = async () => {
          if (textToTranslate !== "") {
            const response = await fetch(
              `https://api.funtranslations.com/translate/${translator}.json?text=${textToTranslate}`
            );
            const data = await response.json();
            const content = await { ...data.contents };
            if (isActive) {
              setTranslatedContent(content);
            }
          }
        };
        startTranslation();
        return () => {
          isActive = false;
        };
      }, [textToTranslate, translator]);
    
      return [translatedContent, dispatch];
    };
    


  • 사용자 입력을 담당할 TextField 구성 요소를 만듭니다
  • .
    TextField.jsx
    import { useState } from "react";
    
    const TextField = ({ dispatch }) => {
      const [userText, setUserText] = useState("");
    
      const handleChange = (evt) => {
        setUserText(evt.target.value);
      };
    
      const handleSubmit = (evt) => {
        evt.preventDefault();
        dispatch({ type: "ENTER_TEXT", payload: { text: userText } });
        setUserText("");
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            onChange={handleChange}
            placeholder="Enter your text here"
            max={50}
            value={userText}
          />
          <button type="submit">Translate</button>
        </form>
      );
    };
    
    export default TextField;
    



  • 이제 6가지 유형의 변환기 구성 요소를 모두 생성합니다.**Yoda.jsx**

  • import TranslateCard from "../components/TranslateCard";
    import { useTranslateText } from "../customHooks/useTranslateText";
    import TextField from "./TextField";
    import Layout from "../components/Layout";
    
    const Yoda = () => {
      const [translatedContent, dispatch] = useTranslateText("yoda");
      return (
        <Layout>
          <TextField dispatch={dispatch} />
          {translatedContent.translated ? (
            <TranslateCard {...translatedContent} />
          ) : null}
        </Layout>
      );
    };
    export default Yoda;
    

    **Minion.jsx**
    import TranslateCard from "../components/TranslateCard";
    import { useTranslateText } from "../customHooks/useTranslateText";
    import TextField from "./TextField";
    import Layout from "../components/Layout";
    
    const Minion = () => {
      const [translatedContent, dispatch] = useTranslateText("minion");
      return (
        <Layout>
          <TextField dispatch={dispatch} />
          {translatedContent.translated ? (
            <TranslateCard {...translatedContent} />
          ) : null}
        </Layout>
      );
    };
    export default Minion;
    
    

    **Dothraki.jsx**
    import TranslateCard from "../components/TranslateCard";
    import { useTranslateText } from "../customHooks/useTranslateText";
    import TextField from "./TextField";
    import Layout from "../components/Layout";
    
    const Dothraki = () => {
      const [translatedContent, dispatch] = useTranslateText("dothraki");
      return (
        <Layout>
          <TextField dispatch={dispatch} />
    
          {translatedContent.translated ? (
            <TranslateCard {...translatedContent} />
          ) : null}
        </Layout>
      );
    };
    export default Dothraki;
    

    **Valyrian.jsx**
    import TranslateCard from "../components/TranslateCard";
    import { useTranslateText } from "../customHooks/useTranslateText";
    import TextField from "./TextField";
    import Layout from "../components/Layout";
    
    const Valyrian = () => {
      const [translatedContent, dispatch] = useTranslateText("valyrian");
      return (
        <Layout>
          <TextField dispatch={dispatch} />
          {translatedContent.translated ? (
            <TranslateCard {...translatedContent} />
          ) : null}
        </Layout>
      );
    };
    export default Valyrian;
    

    **Mandalorian.jsx**
    import TranslateCard from "../components/TranslateCard";
    import { useTranslateText } from "../customHooks/useTranslateText";
    import TextField from "./TextField";
    import Layout from "../components/Layout";
    
    const Mandalorian = () => {
      const [translatedContent, dispatch] = useTranslateText("mandalorian");
      return (
        <Layout>
          <TextField dispatch={dispatch} />
          {translatedContent.translated ? (
            <TranslateCard {...translatedContent} />
          ) : null}
        </Layout>
      );
    };
    export default Mandalorian;
    

    **Shakespeare.jsx**
    import TranslateCard from "../components/TranslateCard";
    import { useTranslateText } from "../customHooks/useTranslateText";
    import TextField from "./TextField";
    import Layout from "../components/Layout";
    
    const Shakespeare = () => {
      const [translatedContent, dispatch] = useTranslateText("shakespeare");
      return (
        <Layout>
          <TextField dispatch={dispatch} />
          {translatedContent.translated ? (
            <TranslateCard {...translatedContent} />
          ) : null}
        </Layout>
      );
    };
    export default Shakespeare;
    



    All done. Now App is good to go.
    For style the app I use Tailwindcss
    Fun Translation API Fun Translation API

    좋은 웹페이지 즐겨찾기