بتل کد Battle Codeدارد باز می‌شود…

جواب «Back to the Box» چالش 3 از جلسه‌ی 31

سؤال

این فهرست خرید کار می‌کند: دکمه‌ی Add و کلید Enter داخل کادر، هر دو نوشته را به فهرست اضافه می‌کنند. ولی بعد از زدن Add نشانگر از کادر بیرون می‌ماند و برای چیز بعدی باید دوباره روی کادر کلیک کرد.
کاری کن که بعد از هر بار اضافه شدن، نشانگر به کادر #box برگردد:
1. یک ref به اسم boxRef بساز.
2. آن را به کادر وصل کن.
3. آخر تابع add نشانگر را داخل کادر بگذار.

راهنما

بالای کامپوننت: const boxRef = useRef(null);. روی input: ref={boxRef}. آخر add: boxRef.current.focus();

یک جواب درست

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
</style>

<div id="root" dir="ltr"></div>

<script type="text/jsx">
import { useState, useRef } from "react";
import { createRoot } from "react-dom/client";

function App() {
  const [text, setText] = useState("");
  const [items, setItems] = useState([]);
  const boxRef = useRef(null);

  function add() {
    if (text === "") {
      return;
    }
    setItems([...items, text]);
    setText("");
    boxRef.current.focus();
  }

  function onKey(e) {
    if (e.key === "Enter") {
      add();
    }
  }

  return (
    <div>
      <input id="box" ref={boxRef} value={text} onChange={(e) => setText(e.target.value)} onKeyDown={onKey} />
      <button id="add" onClick={add}>Add</button>
      <ul id="list">
        {items.map((item, i) => (
          <li key={i}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<App />);
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن