#root
View Compiled
const { useContext, useState, createContext } = React;
const { render } = ReactDOM;

// Initialisation du contexte, en utilisant la forme attendue [valeur, fonction de modification]
const UserContext = createContext(["", () => {}]);

function App() {
  // Création de l'état username contenant ['', fonction de modification]
  const usernameState = useState("");
  return (
    <UserContext.Provider value={usernameState}>
      <UserName />
      <UserNameInput />
    </UserContext.Provider>
  );
}

function UserName() {
  // Récupération de la valeur du contexte
  const [username] = useContext(UserContext);
  return <span>{username}</span>;
}

function UserNameInput() {
  // Récupération de la fonction de modification
  const [username, setUsername] = useContext(UserContext);
  const handleInput = (event) => {
    // Changement de la valeur du contexte
    setUsername(event.target.value);
  };
  return <input type="text" value={username} onChange={handleInput} />;
}

render(<App />, document.getElementById('root'))
View Compiled
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.8.7/polyfill.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js
  3. https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js