Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useEffect, useState } from 'react';
- import cn from 'classnames';
- interface Country {
- id: number;
- name: string;
- description: string;
- }
- const countries: Country[] = [
- { id: 1, name: 'Japan', description: 'bla bla 1'},
- { id: 2, name: 'Italy', description: 'bla bla 2'},
- { id: 3, name: 'Spain', description: 'bla bla 3'},
- ];
- export default function App() {
- console.log('App: render')
- const [opened, setOpened] = useState<boolean>(true);
- const [active, setActive] = useState<Country>(countries[2])
- const tabClickHandler = (tab: Country) => {
- console.log(tab);
- setActive(tab);
- }
- const tabClickHandler2 = (tab: Country) => {
- console.log(tab);
- }
- return (
- <div className="container mt-2">
- <button onClick={() => setOpened(true)}>OPEN</button>
- <button onClick={() => setOpened(false)}>CLOSE</button>
- <Panel title="hello" style={{ width: 200}} isOpen={opened} toggle={() => console.log('ciao')}>
- <input type="text"/>
- <input type="text"/>
- <input type="text"/>
- </Panel>
- <Tabbar <Country>
- data={countries} onTabClick={tabClickHandler} active={active}/>
- <Tabbar data={countries} onTabClick={tabClickHandler2} />
- <img src={'https://maps.googleapis.com/maps/api/staticmap?center=' + active.name + '&zoom=5&size=200x100&key=AIzaSyDSBmiSWV4-AfzaTPNSJhu-awtfBNi9o2k'} alt=""/>
- <div>
- {active.description}
- </div>
- {/* <Tabbar data={....} onTabClick={} active={}></Tabbar>*/}
- </div>
- );
- }
- interface TabbarProps<T> {
- data?: T[];
- active?: T;
- onTabClick: (tab: T) => void
- }
- export const Tabbar = <T extends { id: number, name: string}>(props: TabbarProps<T>) => {
- const [tabActive, setTabActive] = useState<any>()
- useEffect(() => {
- setTabActive(props.active);
- }, [ props.active])
- function tabClickHAndler(item: any) {
- setTabActive(item);
- props.onTabClick(item);
- }
- return (
- <ul className="nav nav-tabs">
- {
- props.data?.map(item => {
- const active = item.id === tabActive?.id;
- return <li key={item.id} className="nav-item" onClick={() => tabClickHAndler(item)}>
- <a className={cn('nav-link', { active })} >{item.name}</a>
- </li>
- })
- }
- </ul>
- )
- }
- // PANEL COMPONENT
- interface PanelProps {
- title: string;
- isOpen: boolean;
- toggle?: () => void;
- }
- const Panel: React.FC<PanelProps & React.HTMLProps<HTMLDivElement>> = props => {
- const [opened, setOpened] = useState<boolean>(true);
- const { children, title, isOpen, toggle, ...rest} = props;
- useEffect(() => {
- setOpened(props.isOpen);
- }, [ props.isOpen])
- function toggleHandler() {
- setOpened(!opened);
- if (props.toggle) {
- props.toggle();
- }
- }
- return (
- <div className={'card'} {...rest}>
- <div className={'card-header'} onClick={toggleHandler}>{props.title}</div>
- { opened && <div className="card-body">{props.children} </div>}
- </div>
- )
- }
Add Comment
Please, Sign In to add comment