Skip to content

Instantly share code, notes, and snippets.

@porfidev
Created July 31, 2022 17:02
Show Gist options
  • Save porfidev/a4bc57d20698f769292f6e14c47a1058 to your computer and use it in GitHub Desktop.
Save porfidev/a4bc57d20698f769292f6e14c47a1058 to your computer and use it in GitHub Desktop.
Actualizar el valor del padre desde el hijo con componentes de clase
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>porfi.dev React JS | Prueba 02</title>
<style>
.TabStrip {
display: flex;
flex-direction: row;
}
.TabStrip .TabStrip-title {
margin-right: 0.6rem;
padding: 0.5rem 1rem;
cursor: pointer;
}
.TabStrip .TabStrip-title-active {
background-color: deeppink;
color: white;
margin-right: 0.6rem;
padding: 0.5rem 1rem;
}
</style>
</head>
<body>
<div id="app_container"></div>
<!-- Cargar React. -->
<!-- Nota: cuando se despliegue, reemplazar "development.js" con "production.min.js". -->
<script
src="https://unpkg.com/react@18/umd/react.development.js"
crossorigin
></script>
<script
src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"
crossorigin
></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
class TabStrip extends React.Component {
render() {
return (
<div className="TabStrip">
{this.props.titles.map((title, index) => {
const className =
"TabStrip-title" +
(this.isActive(index) ? " TabStrip-title-active" : "");
return (
<div
onClick={() => this.setActiveIndex(index)}
key={index}
className={className}
>
{title}
</div>
);
})}
</div>
);
}
isActive(index) {
return index === this.getActiveIndex();
}
setActiveIndex(activeIndex) {
this.props.onActiveIndexChange(activeIndex);
}
getActiveIndex() {
return this.props.activeIndex;
}
}
class App extends React.Component {
state = { activeIndex: 1 };
onActiveIndexChange = (activeIndex) => {
this.setState({activeIndex: activeIndex});
}
render() {
return (
<div>
<TabStrip
activeIndex={this.state.activeIndex}
onActiveIndexChange={this.onActiveIndexChange}
titles={["My account", "Settings", "Dashboard"]}
/>
</div>
);
}
}
const domContainer = document.querySelector("#app_container");
const root = ReactDOM.createRoot(domContainer);
root.render(<App />);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment