Complete the code to lift state up by passing the state setter as a prop.
function Parent() {
const [count, setCount] = React.useState(0);
return <Child onClick=[1] />;
}
function Child({ onClick }) {
return <button onClick={onClick}>Click me</button>;
}The parent passes the setCount function to the child so the child can update the parent's state.
Complete the code to lift state up and handle input changes in the parent.
function Parent() {
const [text, setText] = React.useState('');
return <InputBox value={text} onChange=[1] />;
}
function InputBox({ value, onChange }) {
return <input value={value} onChange={onChange} />;
}The parent handles the input change event and updates the state with the new input value.
Fix the error in lifting state up by completing the code to pass the correct prop name.
function Parent() {
const [selected, setSelected] = React.useState(null);
return <Child [1]={setSelected} />;
}
function Child({ onSelect }) {
return <button onClick={() => onSelect('apple')}>Select Apple</button>;
}The parent must pass the setter function as the onSelect prop to match the child's expected prop name.
Fill both blanks to lift state up and handle multiple inputs in the parent.
function Parent() {
const [form, setForm] = React.useState({ name: '', age: '' });
function handleChange(event) {
const { name, value } = event.target;
setForm({ ...form, [1]: [2] });
}
return <FormInputs form={form} onChange={handleChange} />;
}
function FormInputs({ form, onChange }) {
return (
<>
<input name="name" value={form.name} onChange={onChange} />
<input name="age" value={form.age} onChange={onChange} />
</>
);
}Using computed property names [name] allows updating the correct field dynamically with the new value.
Fill all three blanks to lift state up and filter a list based on input in the parent.
function Parent() {
const [filter, setFilter] = React.useState('');
const items = ['apple', 'banana', 'cherry'];
const filteredItems = items.filter(item => item.[1]([2]) [3] -1);
return (
<>
<FilterInput value={filter} onChange={e => setFilter(e.target.value)} />
<ItemList items={filteredItems} />
</>
);
}
function FilterInput({ value, onChange }) {
return <input value={value} onChange={onChange} placeholder="Filter items" />;
}
function ItemList({ items }) {
return <ul>{items.map(item => <li key={item}>{item}</li>)}</ul>;
}The code filters items by checking if the lowercase item string contains the lowercase filter string using indexOf > -1.