How can React achieve page switching through sliding?
To achieve page transition through swiping in React, you can utilize the React Router library along with some CSS styling.
First, install the React Router library.
npm install react-router-dom
Next, create a component that includes multiple pages, such as the App component.
import React from 'react';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
import './App.css';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
const App = () => {
return (
<Router>
<div className="app">
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</div>
</Router>
);
}
export default App;
In the code above, BrowserRouter is used as the Router component, and three links are defined in the nav section corresponding to the Home, About, and Contact pages. The Switch component is used to ensure that only one route can be matched.
Next, create components for each page, such as the Home component.
import React from 'react';
const Home = () => {
return (
<div>
<h1>Home Page</h1>
<p>Welcome to the home page!</p>
</div>
);
}
export default Home;
Similarly, create components for the About and Contact pages.
Next, add CSS styles to achieve the effect of sliding between pages. Add the following styles to the App.css file.
.app {
display: flex;
height: 100vh;
}
nav {
width: 20%;
background-color: #f0f0f0;
padding: 20px;
}
nav ul {
list-style-type: none;
}
nav ul li {
margin-bottom: 10px;
}
nav ul li a {
text-decoration: none;
color: #000;
}
.content {
flex: 1;
padding: 20px;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
transition: transform 0.3s ease;
}
.content-enter {
transform: translateX(100%);
}
.content-enter-active {
transform: translateX(0);
}
.content-exit {
transform: translateX(0);
}
.content-exit-active {
transform: translateX(-100%);
}
Finally, when running the application and switching pages, the pages will have a sliding transition effect.
Please note that this is just one way to implement sliding page transition, and the specific implementation may vary depending on the project requirements.