Listing 17-10: Using Composition Instead of Context
import React,{useState} from 'react';
const App = () => {
const [username,setUsername] = useState();
if (username) {
return (
<Dashboard>
<Header>
<UserControls>
<WelcomeMessage username={username} />
<Logout setUsername={setUsername} />
</UserControls>
</Header>
</Dashboard>
)
} else {
return <button onClick={()=>setUsername('Chris')}>Login</button>
}
}
const Dashboard = (props) => {
return (<>{props.children}</>);
}
const Header = (props) => {
return (<>{props.children}</>);
}
const UserControls = (props) => {
return (<>{props.children}</>);
}
const WelcomeMessage = (props) => {
return <>Welcome {props.username}!</>
}
const Logout = (props) => {
return <button onClick = {()=>{props.setUsername('')}}>Logout</button>
}
export default App;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.