I am currently using React's redux template and was trying to figure out this one last part of the code. I want to be able to have the page snap to a certain section when you click on an anchored item in the nav bar.
import React, { useState } from "react";
import { useSelector } from "react-redux";
import styled from "styled-components";
const cars = useSelector(selectCars);
<Menu>
{cars &&
cars.map((car, index) => (
<a key={index} href="...">
{car}
</a>
))}
</Menu>;
const Menu = styled.div`
display: flex;
align-items: center;
justify-content: center;
flex: 1;
a {
font-weight: 600;
text-transform: uppercase;
padding: 0 10px;
flex-wrap: no-wrap;
}
@media (max-width: 768px) {
display: none;
}
`;
Here a few select part of the code. Any ideas?
STEP 1
Append #
to the nav's link followed by (preferably) car's ID
<a key={index} href={`#${index}`}>
For the sake of simplicity and the demo I have created for you (check link below), we can use index
from map function.
STEP 2
Attach id={index}
(again, I suggest you go with id={car.id}
) to the HTML element that represents main container of a single car (car section).
DEMONSTRATION
I have created a small example on How to navigate and snap to certain section of a web page in React
P.S. Have in mind that you'll need to handle snap offset in order to properly show curently selected car from the menu. I was using one trick you can find in this answer.