<html>
<head>
<meta charset="UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const { useState } = React
function App() {
const [elements, setElements] = useState([
{ id: 'element1', name: 'Element 1', description: 'This is the first element' },
{ id: 'element2', name: 'Element 2', description: 'This is the second element' },
{ id: 'element3', name: 'Element 3', description: 'This is the third element' }
]);
const scrollToElement = (id) => {
const container = document.getElementById(id);
container.scrollIntoView({ behavior: 'smooth' });
};
return (
<div className='container'>
<h3>React Scroll to element by id</h3>
{elements.map((element, index) => (
<button key={index} onClick={() => scrollToElement(element.id)}>
{element.name}
</button>
))}
{elements.map((element, index) => (
<div key={index} id={element.id} className="element">
<h2>{element.name}</h2>
<p>{element.description}</p>
</div>
))}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
<style>
* {
box-sizing: border-box;
}
.container {
margin: 0 auto;
width: 500px;
text-align: center;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12), 0 2px 4px 0 rgba(0, 0, 0, 0.24);
padding: 20px;
}
h3 {
font-size: 24px;
margin-bottom: 20px;
}
button {
background-color: #007bff;
color: #fff;
border: none;
padding: 10px 20px;
margin-bottom: 10px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #0056b3;
}
.element {
background-color: #f8f9fa;
border-radius: 4px;
padding: 20px;
margin-bottom: 100px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
h2 {
font-size: 20px;
margin-bottom: 10px;
}
p {
font-size: 16px;
color: #555;
}
</style>
</body>
</html>