Lifting State Up: The Mirror
Mission
Share data between sibling components by moving state to their closest common ancestor, so the UI always stays in sync.
Tasks
- 1
Notice that
InputComponentandDisplayComponentare siblings and cannot pass data to each other directly. - 2
Move the state and its setter from
InputComponentup toApp. - 3
Pass the value to
DisplayComponentas a prop. - 4
Pass the update function to
InputComponentso it can change the parent's state. - 5
Type in the input and check that the other component updates in real time.
import React, { useState } from 'react'; // 1. Move the state here so both children can access it export default function App() { return ( <div style={{ padding: '20px', textAlign: 'center', fontFamily: 'sans-serif' }}> <h1>Text Synchronizer</h1> <div style={{ border: '1px solid #ddd', padding: '20px', borderRadius: '8px' }}> <InputComponent /> <hr /> <DisplayComponent /> </div> </div> ); } function InputComponent() { // Remove the state from here const [value, setValue] = useState(""); return ( <div> <label>Type something: </label> <input type="text" value={value} onChange={(e) => setValue(e.target.value)} /> </div> ); } function DisplayComponent() { // 2. This component should receive the text through props return ( <div style={{ marginTop: '20px' }}> <h3>Live result:</h3> <p style={{ color: 'blue', fontSize: '1.5rem' }}> {/* Show the text here */} ... </p> </div> ); }
Requirements
0/6App owns the state (not run yet)
InputComponent has no state of its own (not run yet)
InputComponent receives the value and the update function (not run yet)
DisplayComponent receives the state as a prop (not run yet)
DisplayComponent renders the received text (not run yet)
Does not read the DOM directly (not run yet)
AI mentor
Reviews only the files you changed, plus the checks you missed.
Run the checks first. They are free and instant.