Created
February 20, 2020 05:28
-
-
Save jsmanifest/048f6a8bcdc93a9a581d65579da3f1b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import './styles.css' | |
function Navbar({ | |
items, | |
selectedItem: selectedItemProp, | |
onSelect: onSelectProp = () => {}, | |
}) { | |
const { current: isControlled } = React.useRef(selectedItemProp !== undefined) | |
const [selectedItem, setSelectedItem] = React.useState( | |
isControlled ? selectedItemProp : '/home', | |
) | |
function onClick(value) { | |
return (e) => { | |
if (isControlled) { | |
onSelectProp(value, e) | |
} else { | |
setSelectedItem(value) | |
} | |
} | |
} | |
const selectedItemResult = isControlled ? selectedItemProp : selectedItem | |
return ( | |
<ul> | |
{items.map((item) => ( | |
<li | |
key={item.to} | |
onClick={onClick(item.to)} | |
style={{ | |
listStyle: 'none', | |
display: 'inline-block', | |
marginRight: 15, | |
color: selectedItemResult === item.to ? 'purple' : undefined, | |
}} | |
> | |
{item.label} | |
</li> | |
))} | |
</ul> | |
) | |
} | |
function App() { | |
const [selectedItem, setSelectedItem] = React.useState('/home') | |
const items = [ | |
{ to: '/home', label: 'Home' }, | |
{ to: '/blog', label: 'Blog' }, | |
{ to: '/about', label: 'About' }, | |
{ to: '/contact', label: 'Contact' }, | |
] | |
return ( | |
<div> | |
<Navbar | |
items={items} | |
selectedItem={selectedItem} | |
onSelect={setSelectedItem} | |
/> | |
</div> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment