Skip to content

Instantly share code, notes, and snippets.

@SharpCoder
Last active September 27, 2019 06:46
Show Gist options
  • Select an option

  • Save SharpCoder/3ccc39ac8396c86dfc676831364345bc to your computer and use it in GitHub Desktop.

Select an option

Save SharpCoder/3ccc39ac8396c86dfc676831364345bc to your computer and use it in GitHub Desktop.
import React, { PureComponent, useState } from 'react';
import SlideNavigator from './slider/slideNavigator';
const MyView = ({ className, navigateTo }) => {
return (<h1 style={{backgroundColor: "blue"}} className={className} onClick={() => { navigateTo("view2")} }>Hello, world!</h1>);
};
const MyOtherView = ({ className, navigateBack, navigateTo }) => {
const [navs, setNavs] = useState(0);
return (<h1 style={{backgroundColor: "orange"}} className={className} onClick={() => {
if (navs === 0) {
setNavs(1);
navigateTo("view3");
} else {
setNavs(0);
navigateBack();
}
}}>The stars are lovely today!</h1>);
};
const MyOtherOtherView = ({ className, navigateBack }) => {
return (
<h1 style={{backgroundColor: "pink"}} className={className} onClick={navigateBack}>
And so is Thorbrand!
</h1>
);
}
export default class App extends PureComponent {
render() {
return (
<SlideNavigator defaultName="view1">
<MyView name="view1" key="1" />
<MyOtherView name="view2" key="2" />
<MyOtherOtherView name="view3" key="3" />
</SlideNavigator>
);
}
};
.slide-navigator {
transition-property: left;
transition-duration: .75s;
transition-timing-function: ease-in-out;
position: absolute;
top: 0;
width: 100%;
height: 100%;
}
.slide-navigator.active {
left: 0;
}
.slide-navigator.appended {
left: -100%;
}
.slide-navigator.inactive {
left: 100%;
}
import React, {useState } from 'react';
import "./slideNavigator.css";
const SlideNavigator = ({ defaultName, children }) => {
const [history, setHistory] = useState([]);
const [activePage, setActivePage] = useState(defaultName);
const navigateTo = (pageName, silent = false) => {
if (!silent) {
history.push(activePage);
setHistory(history);
}
setActivePage(pageName);
};
const navigateBack = () => {
history.length > 0 && navigateTo(history.pop(), true);
};
const createInstance = (viewInstance, additionalProps) => {
return React.createElement(viewInstance.type, {
children: viewInstance.props.children,
navigateTo,
navigateBack,
key: viewInstance.key,
...additionalProps,
...viewInstance.props,
});
};
return (<React.Fragment>{
React.Children.map(children, (viewInstance) => {
let className = 'slide-navigator ';
let instanceName = viewInstance && viewInstance.props && viewInstance.props.name;
if (history.length > 0 && history.indexOf(instanceName) >= 0) {
className += 'appended';
} else if (instanceName === activePage) {
className += 'active';
} else {
className += 'inactive';
}
return createInstance(viewInstance, { className });
})
}</React.Fragment>);
};
export default SlideNavigator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment