Tabs
by Allie Yu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Babel + JSX
////////////////////////////////////////////////////////////////////////////////
// Exercise:
//
// - Render a tab for each country with its name in the tab
// - Make it so that you can click on a tab and it will appear active
// while the others appear inactive
// - Make it so the panel renders the correct content for the selected tab
//
// Got extra time?
//
// - Make <Tabs> generic so that it doesn't know anything about
// country data (Hint: good propTypes help)
///////////////////////////////////////////////////////////////////////////////
const DATA = [
{ id: 1, name: "Tab A",description: "AAA"},
{ id: 2, name: "Tab B", description: "BBB"},
{ id: 3, name: "Tab C", description: "CCC"}
];
class Tabs extends React.Component {
state = {
activeTabIndex: 0
};
selectTab = index => {
this.setState({
activeTabIndex: index
});
};
render() {
const countryTabs = this.props.data.map((country, idx) => {
return (
<div
className="Tab"
onClick={() => this.selectTab(idx)}
style={
idx === this.state.activeTabIndex ? styles.activeTab : styles.tab
}
>
{country.name}
</div>
);
});
return (
<div className="Tabs">
{countryTabs}
<div className="TabPanel" style={styles.panel}>
{this.props.data[this.state.activeTabIndex].description}
</div>
</div>
);
}
}
class App extends React.Component {
render() {
return (
<div>
<h1>Countries</h1>
<Tabs data={this.props.countries} />
</div>
);
}
}
const styles = {};
styles.tab = {
display: "inline-block",
padding: 10,
margin: 10,
borderBottom: "4px solid",
borderBottomColor: "#ccc",
cursor: "pointer"
};
styles.activeTab = {
...styles.tab,
borderBottomColor: "#000"
};
styles.panel = {
padding: 10
};
ReactDOM.render(<App countries={DATA} />, document.getElementById("root"));