scrollIntoView whole page shifting down - javascript

I want to build an indexed letters. When I click the letter (for example A,B,C). It should be scrolling to the belongs title. I used scrollIntoView here. Everythings okey except "block:start". When I want to the scrolling to title of start, whole page scrolling with container.
Here my gif about issue
Here my html & css & javascript code.
const scrollTo = id => {
let ref = document.getElementById(id)
if (ref /* + other conditions */) {
ref.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "start",
})
}
}
<div className="glossary">
<div className="glossary-items grid">
<div className="d-flex ">
<div className="glossary-letters ">
<ul>
{letter.map(item => (
<li onClick={() => scrollTo(item)}>
<a> {item}</a>
</li>
))}
</ul>
</div>
<div className="glossary-titles">
<ul>
{glossary.map((item, index) => (
<div key={item.group}>
<li id={item.group}>{item.group}</li>
{item.children.map((item2, i) => (
<li key={i}>
<Link
activeClassName="glossary-titles-active"
to={`/en/sozluk/${item2.first_name + item2.id}`}
>
{item2.first_name}
</Link>
</li>
))}
</div>
))}
</ul>
</div>
</div>
<div className="glossary-content ml-5">
<Router>
<Glossary path="en/sozluk/:id" />
</Router>
</div>
</div>
</div>

There is related question to that
You could use scrollTo function of the parent element to scroll to specific child element.
Example
const { useState, useEffect, useRef } = React;
const App = () => {
const [list, setList] = useState([]);
const [keywords, setKeywords] = useState([]);
const refs = useRef(null);
const parentRef = useRef(null);
useEffect(() => {
const newList = Array(25).fill(0).map((pr, index) => String.fromCharCode(65 + index));
const newKeywords = newList.flatMap(pr => [pr, ...newList.map(npr => pr + npr)]);
refs.current = newList.reduce((acc, letter) => {
acc[letter] = React.createRef();
return acc;
}, {});
setList(newList);
setKeywords(newKeywords);
}, [])
const onClick = ({target: {dataset: {letter}}}) => {
const element = refs.current[letter].current;
const parent = parentRef.current;
const onScroll = () => {
const relativeTop = window.scrollY > parent.offsetTop ? window.scrollY : parent.offsetTop
parent.scrollTo({
behavior: "smooth",
top: element.offsetTop - relativeTop
});
}
window.removeEventListener("scroll", onScroll);
window.addEventListener("scroll", onScroll);
onScroll();
/*
element.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "start",
})
*/
}
const tryAssignRef = (letter) => {
return list.indexOf(letter) > -1 ? {ref: refs.current[letter]} : {};
}
/// ...{ref: {refs.current['A']}}
return <div className="container">
<div className="header">
</div>
<div className="body">
<div className="left">
<div className="letters">{list.map(pr => <div className="letter" onClick={onClick} data-letter={pr} key={pr}>{pr}</div>)}</div>
<div ref={parentRef} className="keywords">{keywords.map(pr => <div {...tryAssignRef(pr)} key={pr}>{pr}</div>)}</div>
</div>
<div className="right">
</div>
</div>
</div>
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
.container, .body, .left {
display: flex;
}
.container {
flex-direction: column;
}
.header {
flex: 0 0 100px;
border: 1px solid black;
}
.body {
height: 1000px;
}
.left {
flex: 1;
}
.right {
flex: 2;
}
.left {
justify-content: space-between;
}
.letter {
padding: 2px 0;
cursor: pointer;
}
.letters, .keywords {
padding: 0 10px;
}
.keywords {
overflow-y: scroll;
}
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<div id="root"></div>

Related

ReactJS: How to play video which comes in center and pause all other videos

In maplist I have 20 items that is 20 videos I want to do is play video which comes in center of viewport and pause all others and keep that behaviour throughout scrolling:
const [reels, setReels] = useState([]);
useEffect(() => {
fetchAllVideos();
}, []);
const fetchAllVideos = async () => {
const getAllVideosRes = await getAllVideos(pageNumber);
setReels(getAllVideosRes);
};
return (
<>
reels.map((item, idx) => {
return (
<MDBox mb={3} key={idx}>
<Card sx={{ borderRadius: "25px" }}>
<video style={{ height: "100%", width: "100%", objectFit: "cover", borderRadius: "25px", }} loop controls>
<source src={item.photo} type="video/mp4" />
</video>
</MDBox>
</Card>
</MDBox >
);
})
</>
)
Use an intersectionObserver to track the items as they enter or leave the container.
Set the threshold to be 100% of the element (threshold: 1), and the rootMargin to limit the intersection area to the center of the container (rootMargin: '-20% 0% -20% 0%').
const { useRef, useState, useEffect, useCallback } = React
const usePlayIntersection = () => {
const containerRef = useRef();
const [observer, setObserver] = useState();
useEffect(() => {
const cb = entries => {
entries.forEach(({ isIntersecting, target, intersectionRect }) => {
if(isIntersecting) target.play()
else target.pause()
})
};
const obs = new IntersectionObserver(cb, {
root: containerRef.current,
rootMargin: '-20% 0% -20% 0%',
threshold: 1
})
setObserver(obs)
return () => {
obs.disconnect()
}
}, [])
const observe = useCallback(el => {
if(observer) observer.observe(el)
}, [observer])
return [observe, containerRef]
}
const Demo = ({ videos }) => {
const [observe, containerRef] = usePlayIntersection();
return (
<div className="container" ref={containerRef}>
<div className="filler" />
{videos.map(vid => (
<video
ref={observe}
muted
key={vid}
loop controls>
<source src={vid} type="video/mp4" />
</video>
))}
<div className="filler" />
</div>
)
}
const videos = ["http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4","http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4","http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/VolkswagenGTIReview.mp4","http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/WeAreGoingOnBullrun.mp4","http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/WhatCarCanYouGetForAGrand.mp4"]
ReactDOM
.createRoot(root)
.render(<Demo videos={videos} />)
html, body {
margin: 0;
padding: 0;
}
.container {
height: 100vh;
overflow: auto;
}
video, .filler {
display: block;
margin: 1em;
height: 40%;
width: 40%;
objectFit: cover;
borderRadius: 25px;
}
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="root"></div>

How to change div background on click in React js?

I am fetching a list of questions from the Question.js file to Home.js
How can I change the answer border color when the user clicks on that.
I want to make green if the user clicks on the right answer and red if the user clicks on the wrong answer.
If the user clicks on the wrong answer then it should show the right answer by making the background green and the rest all should become the red border.
See output:
Home.js file:
import React from 'react'
import Questions from './Questions'
const Home = () => {
function action(){
}
return (
<>
<div className="main">
{
Questions.map((item)=>(
<div className="box">
<div className="title">
<h2 className="qno">{item.numb}</h2>
<h2> {item.question}</h2>
</div>
<div className="options">
<span onClick={()=>action()} >{item.options.q1}</span>
<span>{item.options.q2}</span>
<span>{item.options.q3}</span>
<span>{item.options.q4}</span>
</div>
</div>
))
}
</div>
</>
)
}
export default Home;
Questions.js file:
let Questions = [
{
numb: 1,
question: "What does HTML stand for?",
answer: "Hyper Text Markup Language",
options: {
q1: "Hyper Text Preprocessor",
q2: "Hyper Text Markup Language",
q3: "Hyper Text Multiple Language",
q4: "Hyper Tool Multi Language",
},
},
{
numb: 2,
question: "Who is Ankit Yadav?",
answer: "Engineer",
options: {
q1: "Engineer",
q2: "Doctor",
q3: "CEO",
q4: "Scientist",
},
},
];
export default Questions;
style.css file:
/* styling */
.main{
width: 70vw;
height: 100%;
box-shadow: 0 0 14px 0;
margin: 30px auto;
border-radius: 5px;
}
.box{
padding: 10px;
border-bottom: 2px solid #4c4c4c;
}
.title .qno{
font-size: 1.7rem;
font-weight: 800;
font-family: 'Courier New', Courier, monospace;
background-color: #4c4c4c;
padding: 5px;
border-radius: 70px;
color: #fff;
}
.title h2{
font-size: 1.7rem;
font-weight: 500;
margin-left: 10px;
}
.box .title{
display: flex;
}
.options{
display: flex;
flex-direction: column;
justify-content: space-between;
margin: 20px 25px;
}
You can achieve it using inline styles and a few util functions
const Home = () => {
const [answerStatus, setAnswerStatus] = useState(() => {
return Questions.map((item) => {
return {
numb: item.numb,
answered: false,
givenAnswer: ""
};
});
});
const action = (questionNumber, answer) => {
setAnswerStatus((prevState) => {
return prevState.map((item) =>
item.numb === questionNumber
? { ...item, answered: true, givenAnswer: answer }
: item
);
});
};
const isAnswerCorrect = (questionNumber) => {
const status = answerStatus.find((item) => item.numb === questionNumber);
const question = Questions.find((item) => item.numb === questionNumber);
return status.answered && question.answer === status.givenAnswer;
};
const questionAnswered = (questionNumber) => {
const status = answerStatus.find((item) => item.numb === questionNumber);
return status.answered;
};
const getGivenAnswer = (questionNumber) => {
return answerStatus.find((item) => item.numb === questionNumber)
?.givenAnswer;
};
return (
<>
<div className="main">
{Questions.map((item) => (
<div className="box">
<div className="title">
<h2 className="qno">{item.numb}</h2>
<h2> {item.question}</h2>
</div>
<div className="options">
{Object.entries(item.options).map(([optionId, optionDesc]) => {
return (
<span
onClick={() => action(item.numb, optionDesc)}
style={{
backgroundColor: questionAnswered(item.numb)
? isAnswerCorrect(item.numb) &&
getGivenAnswer(item.numb) === optionDesc
? "lightgreen"
: isAnswerCorrect(item.numb)
? "lightblue"
: item.answer !== optionDesc
? "tomato"
: "lightgreen"
: "lightblue",
padding: "5px",
borderRadius: "3px",
margin: "3px",
cursor: "pointer"
}}
>
{optionDesc}
{questionAnswered(item.numb) &&
getGivenAnswer(item.numb) === optionDesc &&
" (given answer)"}
</span>
);
})}
</div>
</div>
))}
</div>
</>
);
};
export default Home;
Code sandbox => https://codesandbox.io/s/quirky-hill-cwoc5?file=/src/App.js
I would recommend to create separate component called Question to avoid working with arrays of data and put state login inside. But if this is not possible I would do it this way:
Home.js
import React from 'react'
import Questions from './Questions'
const Home = () => {
// Add this two state values
const { highlightedRightIds, setHighlightedRightIds } = useState([]);
const { highlightedWrongIds, setHighlightedWrongIds } = useState([]);
// Handle click here
const handleClick = (questionId, isRight) => {
setHighlightedWrongIds([...highlightedWrongIds, questionId]);
if (isRight) {
setHighlightedRightIds([...highlightedRightIds, questionId]);
}
}
return (
<>
<div className="main">
{
Questions.map((item)=>(
<div className="box">
<div className="title">
<h2 className="qno">{item.numb}</h2>
<h2> {item.question}</h2>
</div>
<div className="options">
{
// use map to render a list of options
item.options.map(option => {
const isRight = option === item.answer;
const highlight = isRight
? highlightedRightIds.includes(item.numb)
: highlightedWrongIds.includes(item.numb);
const highlightClass = isRight
? "rightAnswer"
: "wrongAnswer";
return <span
onClick={() => handleClick(item.numb, isRight)}
className={highlight ? highlightClass : ""}
>
{option}
</span>;
})
}
</div>
</div>
))
}
</div>
</>
)
}
export default Home;
style.css (add new classes)
// ... other styles
.rightAnswer{
background-color: green;
}
.wrongAnswer{
border-color: red;
}

Click OutSide co close sidebar reactjs

I create a function when I click outside of the sidebar it will hide it and I also have a button that toggles show and hide the sidebar. But when I combined both of them together, the button did not work properly, it only show the sidebar but can't close it, only when I click outside it will close the sidebar
Click OutSide to close function:
const ref = useRef(null);
useEffect(() => {
document.addEventListener("mousedown", Clickout);
return () => {
document.removeEventListener("mousedown", Clickout);
};
}, []);
const Clickout = (eve) => {
if (ref.current && !ref.current.contains(eve.target)) {
setShow(false);
}
};
My Return:
return (
<header>
<div className="head">
<div className="logo">
<img src={logo} alt="logo" />
</div>
<button
className="burger"
onClick={() => {
setShow(!showMenu);
console.log("here");
}}
>
<div className={`${showMenu ? "change" : ""} bur1 `}></div>
<div className={`${showMenu ? "change" : ""} bur2 `}></div>
<div className={`${showMenu ? "change" : ""} bur3 `}></div>
</button>
</div>
<nav className={showMenu ? "active" : ""} ref={ref}>
<ul>
{navItem.map((item) => {
const { id, url, text } = item;
return (
<li key={id}>
<a href={url}>{text}</a>
</li>
);
})}
</ul>
</nav>
</header>
);
};
Nav bar CSS:
nav {
position: fixed;
right: -100%;
top: 0;
width: 60%;
height: 100vh;
text-align: center;
padding-top: 15vh;
transition: 0.8s ease;
background-color: blue;
}
nav.active {
right: 0;
transition: 0.5s;
}
Thank you.
you can use another state for manage button onclick when menu is open:
const [disableBtn, setDisableBtn] = useState(false);
and in Clickout function manage it:
const Clickout = (eve) => {
if (showMenu && ref.current && !ref.current.contains(eve.target)) {
setShow(false);
setDisableBtn(true)
} else {
setDisableBtn(false)
}
};
and in button for onclick use condition:
if (!disableBtn) setShow(true);
Updating state this way setShow(!showMenu) does not immediately update the state.Rather it schedules the update(You can read the docs). When your setState depends on your previous state (in this case showMenu depends on previous state) use this technique: (prev) => setState(!prev) instead. So, simply updating your onClick will solve the issue.
<button className="burger"
onClick={() => {
(prevShowMenu) => setShow(!prevShowMenu)
}}>
(Let me know in the comments if this was helpful)

React - displaying images side by side

QUESTION
I have a few photos saved as png files that are in the same folder as the React component and are imported correctly as well.
How and what would be a good practice way to display all the images, let's say there are 4 images, in their proper box shown in the picture below and have them be displayed side by side, along with their name/price aligned below the image.
Similar to craigslist's gallery setting when looking at posts with images.
Ex:
<img src={Logo} alt=“website logo”/>
<img src={Mogo} alt=“website mogo”/>
<img src={Jogo} alt=“website jogo”/>
<img src={Gogo} alt=“website gogo”/>
Could I do something with products.map((product, index, image?))...?
CODE
const Product = props => {
const { product, children } = props;
return (
<div className="products">
{product.name} ${product.price}
{children}
</div>
);
};
function App() {
const [products] = useState([
{ name: "Superman Poster", price: 10 },
{ name: "Spider Poster", price: 20 },
{ name: "Bat Poster", price: 30 }
]);
const [cart, setCart] = useState([]);
const addToCart = index => {
setCart(cart.concat(products[index]));
};
const calculatePrice = () => {
return cart.reduce((price, product) => price + product.price, 0);
};
return (
<div className="App">
<h2>Shopping cart example using React Hooks</h2>
<hr />
{products.map((product, index) => (
<Product key={index} product={product}>
<button onClick={() => addToCart(index)}>Add to cart</button>
</Product>
))}
YOUR CART TOTAL: ${calculatePrice()}
{cart.map((product, index) => (
<Product key={index} product={product}>
{" "}
</Product>
))}
</div>
);
}
Wrap the list of products with a div (<div className="productsContainer">), and display it as a flex with wrap.
Set the width of the items (products) to 50% or less.
To render the image, render the <img> tag as one of the children, or add it directly to the product. Also change the data to include the src.
const { useState } = React;
const Product = ({ product, children }) => (
<div className="products">
{product.name} ${product.price}
{children}
</div>
);
function App() {
const [products] = useState([
{ name: "Superman Poster", price: 10, logo: 'https://picsum.photos/150/150?1' },
{ name: "Spider Poster", price: 20, logo: 'https://picsum.photos/150/150?2' },
{ name: "Bat Poster", price: 30, logo: 'https://picsum.photos/150/150?3' }
]);
const [cart, setCart] = useState([]);
const addToCart = index => {
setCart(cart.concat(products[index]));
};
const calculatePrice = () => {
return cart.reduce((price, product) => price + product.price, 0);
};
return (
<div className="App">
<h2>Shopping cart example using React Hooks</h2>
<hr />
<div className="productsContainer">
{products.map((product, index) => (
<Product key={index} product={product}>
<img src={product.logo} alt="website logo" />
<button onClick={() => addToCart(index)}>Add to cart</button>
</Product>
))}
</div>
YOUR CART TOTAL: ${calculatePrice()}
{cart.map((product, index) => (
<Product key={index} product={product}>
{" "}
</Product>
))}
</div>
);
}
ReactDOM.render(
<App />,
root
);
* {
box-sizing: border-box;
}
.productsContainer {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.products {
display: flex;
flex-direction: column;
align-items: center;
width: 45%;
margin: 0 0 1em 0;
padding: 1em;
border: 1px solid black;
}
.products img {
margin: 0.5em 0;
}
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>
Best way to display those side by side you can display it by giving css classes flex-row for horizontal view and flex-column for vertical view in the main div component
const Product = props => {
const { product, children, image } = props;
return (
<div className="products">
{product.name} ${product.price} ${product.image}
{children}
</div>
);
};
products.map((product, index, image?))...?
Something along the lines of this?

Reactjs dropdown menu not displaying when hovered over the word

can someone tells me why the dropdown menu is not displaying in this demo? the dropdown menu should show when I hover over the word 'collective'?
https://codesandbox.io/s/funny-river-c76hu
For the app to work, you would have to type in the input box "collective", click analyse, then a progressbar will show, click on the blue line in the progressbar, an underline would show under the word "collective" then you should hover over "collective" word and a drop down menu should be displayed but the whole window disappears when I hover over the word "collective" instead of the drop down menu
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { Content, Dropdown, Label, Progress, Button, Box } from "rbx";
import "rbx/index.css";
function App() {
const [serverResponse, setServerResponse] = useState(null);
const [text, setText] = useState([]);
const [loading, setLoading] = useState(false);
const [modifiedText, setModifiedText] = useState(null);
const [selectedSentiment, setSentiment] = useState(null);
const [dropdownContent, setDropdownContent] = useState([]);
const [isCorrected, setIsCorrected] = useState(false);
const [displayDrop, setDisplayDrop] = useState(false);
useEffect(() => {
if (serverResponse && selectedSentiment) {
const newText = Object.entries(serverResponse[selectedSentiment]).map(
([word, recommendations]) => {
const parts = text[0].split(word);
const newText = [];
parts.forEach((part, index) => {
newText.push(part);
if (index !== parts.length - 1) {
newText.push(
<u
className="dropbtn"
data-replaces={word}
onMouseOver={() => {
setDropdownContent(recommendations);
setDisplayDrop(true);
}}
>
{word}
</u>
);
}
});
return newText;
}
);
setModifiedText(newText.flat());
}
}, [serverResponse, text, selectedSentiment]);
const handleAnalysis = () => {
setLoading(true);
setTimeout(() => {
setLoading(false);
setServerResponse({ joy: { collective: ["inner", "constant"] } });
}, 1500);
};
const handleTextChange = event => {
setText([event.target.innerText]);
};
const replaceText = wordToReplaceWith => {
const replacedWord = Object.entries(serverResponse[selectedSentiment]).find(
([word, recommendations]) => recommendations.includes(wordToReplaceWith)
)[0];
setText([
text[0].replace(new RegExp(replacedWord, "g"), wordToReplaceWith)
]);
setModifiedText(null);
setServerResponse(null);
setIsCorrected(true);
setDropdownContent([]);
};
const hasResponse = serverResponse !== null;
return (
<Box>
<Content>
<div
onInput={handleTextChange}
contentEditable={!hasResponse}
style={{ border: "1px solid red" }}
>
{hasResponse && modifiedText
? modifiedText.map((text, index) => <span key={index}>{text}</span>)
: isCorrected
? text[0]
: ""}
</div>
<br />
{displayDrop ? (
<div
id="myDropdown"
class="dropdown-content"
onClick={() => setDisplayDrop(false)}
>
dropdownContent.map((content, index) => (
<>
<strong onClick={() => replaceText(content)} key={index}>
{content}
</strong>{" "}
</>
))
</div>
) : null}
<br />
<Button
color="primary"
onClick={handleAnalysis}
disabled={loading || text.length === 0}
>
analyze
</Button>
<hr />
{hasResponse && (
<Label>
Joy{" "}
<Progress
value={Math.random() * 100}
color="info"
onClick={() => setSentiment("joy")}
/>
</Label>
)}
</Content>
</Box>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
css file
.App {
font-family: sans-serif;
text-align: center;
}
.highlight {
background: red;
text-decoration: underline;
}
.dropbtn {
color: white;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover,
.dropbtn:focus {
background-color: #2980b9;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
position: relative;
background-color: #f1f1f1;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
.show {
display: block;
}
The problem is this:
{displayDrop ? (
<div
id="myDropdown"
class="dropdown-content"
onClick={() => setDisplayDrop(false)}
>
dropdownContent.map((content, index) => (
<>
<strong onClick={() => replaceText(content)} key={index}>
{content}
</strong>{" "}
</>
))
</div>
) : null}
You are missing a pair of curly brackets around dropdownContent. It should be:
{displayDrop ? (
<div
id="myDropdown"
class="dropdown-content"
onClick={() => setDisplayDrop(false)}
>
{dropdownContent.map((content, index) => (
<>
<strong onClick={() => replaceText(content)} key={index}>
{content}
</strong>{" "}
</>
))}
</div>
) : null}
A working sandbox here https://codesandbox.io/embed/fast-feather-lvpk7 which is now displaying this content.

Categories

Resources