How to work from query selector to useRef in React? - javascript

I have a typewrite effect function. Now I want to show the code (the effect) in the div (typingRef), I made something like typingRef.current = letter but is that the same as document.querSelector('typing').textContent = letter? I want to work with the ref not the queryselector
export function Text({ children }) {
const headingRef = React.useRef(null)
const typingRef = React.useRef(null)
const texts = ['websites', 'applications', 'mobile' ]
React.useEffect(() => {
let count = 0
let index = 0
let currentText = ''
let letter = ''
function type() {
if (count === texts.length) {
count = 0
}
currentText = texts[count]
letter = currentText.slice(0, ++index)
typingRef.current = letter
if (letter.length === currentText.length) {
count++
index = 0
}
setTimeout(type, 400)
}
type()
})
return (
<div className={styles.component}>
<div className={styles.intro}>
<h1 ref={headingRef} className={styles.heading}>
{ children }
</h1>
<div ref={typingRef} className={styles.typing} />
</div>
</div>
)
}

Best I can come up with from trying to understand your question. Try this: typingRef.current.innerHTML
export const Text = ({ children }) => {
const headingRef = React.useRef(null)
const typingRef = React.useRef(null)
const texts = ['websites', 'applications', 'mobile' ]
React.useEffect(() => {
let count = 0
let index = 0
let currentText = ''
let letter = ''
function type() {
if (count === texts.length) {
count = 0
}
currentText = texts[count]
letter = currentText.slice(0, ++index)
typingRef.current.innerHTML = letter
if (letter.length === currentText.length) {
count++
index = 0
}
setTimeout(type, 400)
}
type()
})
return (
<div>
<div>
<h1 ref={headingRef}>
{ children }
</h1>
<div ref={typingRef}/>
</div>
</div>
)
}

Related

How to make the dropdown option of a select box

I'm building a train web booking project. Now I need to build a selectbox and the option value is varied based on the booking form.
//select-box
<custom-select-box
label="Travel"
v-model="form.InfantWithAdult"
:items="travel"
></custom-select-box>
Try with forEach:
travelWith() {
let travellerlist = [];
let adults = this.passengers.filter(
(x) =>
x.PaxType === "ADT" &&
x.SSR.Outbound.filter((y) => {
return y.codeType === "INFT";
}).length > 0
);
if (adults.length > 0) {
let nr = 1;
let travel = null;
// 👇 loop all adults and add to travellerlist array
adults.forEach(adult => {
if (!adult.FirstName) {
travel = `Adult ${nr++}`;
} else if (adult.FirstName !== "" && adult.LastName !== "") {
travel = `Adult ${nr++} ${adult.Title} ${adult.FirstName} ${adult.LastName}`;
}
travellerlist.push(travel);
})
}
return travellerlist;
},

What's wrong with my code, click event fires only once JavaScript?

The loop works only once and then nothing happens. I have three testimonials, and can go only once forward or backwords.Thanks for help!
const nextBtn = document.querySelector(".next-btn");
const prevBtn = document.querySelector(".prev-btn");
const testimonials = document.querySelectorAll(".testimonial");
let index = 0;
window.addEventListener("DOMContentLoaded", function () {
show(index);
});
function show(index) {
testimonials.forEach((testimonial) => {
testimonial.style.display = "none";
});
testimonials[index].style.display = "flex";
}
nextBtn.addEventListener("click", function () {
index++;
if (index > testimonials.length - 1) {
index = 0;
}
show(index);
});
prevBtn.addEventListener("click", function () {
index--;
if (index < 0) {
index = testimonials.length - 1;
}
show(index);
});
I would use a "hidden" class to hide the non-active testimonials instead of manipulating the element's style in-line. Also, your navigation logic can be simplified to a modulo operation.
The code your originally posted seemed to work out well, but it seems to cluttered with redundancy (code reuse). It also lacks structural flow (readability).
const
modulo = (n, m) => (m + n) % m,
moduloWithOffset = (n, m, o) => modulo(n + o, m);
const
nextBtn = document.querySelector('.next-btn'),
prevBtn = document.querySelector('.prev-btn'),
testimonials = document.querySelectorAll('.testimonial');
let index = 0;
const show = (index) => {
testimonials.forEach((testimonial, currIndex) => {
testimonial.classList.toggle('hidden', currIndex !== index)
});
}
const navigate = (amount) => {
index = moduloWithOffset(index, testimonials.length, amount);
show(index);
}
// Create handlers
const onLoad = (e) => show(index);
const onPrevClick = (e) => navigate(-1);
const onNextClick = (e) => navigate(1);
// Add handlers
window.addEventListener('DOMContentLoaded', onLoad);
nextBtn.addEventListener('click', onNextClick);
prevBtn.addEventListener('click', onPrevClick);
.testimonial {
display: flex;
}
.testimonial.hidden {
display: none;
}
<div>
<button class="prev-btn">Prev</button>
<button class="next-btn">Next</button>
</div>
<div>
<div class="testimonial">A</div>
<div class="testimonial">B</div>
<div class="testimonial">C</div>
<div class="testimonial">D</div>
<div class="testimonial">E</div>
<div class="testimonial">F</div>
</div>

this is undefined when calling child function through a parent function

UPDATE: I have figured out a muuuuch simpler workaround by sing in the typescript file so the JS parent is no longer needed. ~facepalm~ Thanks for all your suggestions!
I am trying to get a button to trigger the function affTimer() inside the child function component but I keep getting the error "this is undefined" in relation to the function call. Here is the two code files:
affType.js
import React, {Component} from 'react';
import ReactPlayer from 'react-player'
import { Link } from 'react-router-dom';
import affirmationService from '../Services/requestService'
import affTrack from '../audio/inner.wav';
import warn from '../audio/warning.wav';
import Player from '../Player/Player';
import videoBG from '../videos/InnerStrength.mp4';
import Type from '../Type/Type.tsx';
import Button from "../customButton";
import {tXP} from '../Type/Type.tsx';
class affType extends Component {
constructor(props) {
super(props);
this.state = {character: undefined};
this.child = React.forwardRef();
this.startGame = this.startGame.bind(this);
}
async componentDidMount() {
const { match: { params } } = this.props;
//let affirmation_id = params.affirmation_id;
//let response = await affirmationService.getById(affirmation_id);
//this.setState({character: response.data});
setTimeout(() => {
document.getElementById('overlay_blk_fast').style.opacity = 0;
setTimeout(() => {
document.getElementById('overlay_blk_fast').style.display = 'none';
}, 1000);
}, 10);
}
spawnDialog() {
document.getElementById('overlay_1').style.display = 'block';
setTimeout(() => {
document.getElementById('overlay_1').style.opacity = 1;
}, 10);
}
destroyDialog() {
document.getElementById('overlay_1').style.opacity = 0;
setTimeout(() => {
document.getElementById('overlay_1').style.display = 'none';
}, 1000);
}
repeat() {
document.getElementById('overlay_2').style.opacity = 0;
document.querySelector('video').play();
setTimeout(() => {
document.getElementById('overlay_2').style.display = 'none';
}, 1000);
}
test_ended() {
document.getElementById('overlay_2').style.display = 'block';
setTimeout(() => {
document.getElementById('audio_end').play();
document.getElementById('overlay_2').style.opacity = 1;
}, 10);
}
startGame() {
var track = document.getElementById('aff');
track.play();
this.child.current.affTimer();
}
render() {
return (
<div>
<div className="contentplayer">
<audio id='aff'><source src={affTrack} /></audio>
<video autoPlay muted loop id="myVideo">
<source src={videoBG} type="video/mp4" />
</video>
<audio id="audio_end" src="/Audio/Inner Strength completed quest - play with completed quest prompt.wav"/>
</div>
<p>{tXP}</p>
<Button
border="none"
color="pink"
height = "200px"
onClick={this.startGame}
radius = "50%"
width = "200px"
children = "Start!"
/>
<Type ref={this.child}>
</Type>
<div className="aligntopright" onClick={() => {this.spawnDialog()}}>
<div className="backbtn-white"></div>
</div>
<div className="overlay_blk_fast" id="overlay_blk_fast"></div>
<div className="overlay" id="overlay_1">
<div className="dialog">
<div className="dialogcontainer">
<img className="dialogbg"/>
<h3 className="dialogtext">Are you sure you would like to go back to the selection page?</h3>
<h2 className="no" onClick={() => {this.destroyDialog()}}>No</h2>
<Link to="/affirmation"><h2 className="yes">Yes</h2></Link>
</div>
</div>
</div>
<div className="overlay" id="overlay_2">
<div className="dialog">
<div className="dialogcontainer">
<img className="dialogbg"/>
<h3 className="dialogtext">Would you like to repeat this quest?</h3>
<Link to="/affirmation"><h2 className="no">Go back</h2></Link>
<h2 className="yes" onClick={() => {this.repeat()}}>Repeat</h2>
</div>
</div>
</div>
</div>
)
}
}
export default affType;
type.tsx
import React, {Component} from 'react';
import useTypingGame from "react-typing-game-hook";
import { textSpanContainsTextSpan } from 'typescript';
var xpM = 0;
var i = 0;
var err = 0;
var xp = 5;
var tXP = 0;
var addXP = 1;
var bonus = 0;
var bonusCounter = 0;
//var warnP = new Audio({warn});
//var affTrackP = new Audio('../audio/inner.wav');
function TypeF() {
let text_array = [
"There is strength and solidity within me",
"Courage is flooding through my veins",
"I possess strength within my heart",
"I am leading the charge with courage, and a vigorous resolution",
"There is a force inside me that is unbelievably powerful",
"There is a brave, radiant spirit inside me",
"I am a tall tree, with thick and strong roots",
"I was born for this",
"There is a divinity within",
"I am a force of nature",
"I possess the mental fortitude of those who climb the highest peaks",
"I was born with a determined spirit",
"There is an intensity in my eyes"
];
let text = text_array[i];
const {
states: {
charsState,
length,
currIndex,
currChar,
correctChar,
errorChar,
phase,
startTime,
endTime
},
actions: { insertTyping, resetTyping, deleteTyping }
} = useTypingGame(text);
const handleKey = (key: any) => {
if (key === "Escape") {
resetTyping();
} else if (key === "Backspace") {
deleteTyping(false);
} else if (key.length === 1) {
insertTyping(key);
}
};
if (currIndex + 1 === length) {
xpM = xpM + 1;
bonusCounter = bonusCounter + 1;
err = err + errorChar;
addXP = ((xp * correctChar) - (err * 2)) * xpM;
if (err > correctChar) {
addXP = correctChar * 3;
}
tXP = tXP + addXP;
if (bonusCounter >= 5) {
bonus = bonus + 1;
bonusCounter = 0;
}
resetTyping();
}
var tmr;
var cd = 18;
function affTimer() {
tmr = setInterval(tock, 1000);
if (i >= text_array.length) {
clearInterval(tmr);
}
}
function tock() {
if (cd > 0) {
cd = cd - 1;
console.log(cd);
}
else if (cd <= 0) {
if (i < text_array.length) {
i = i + 1;
cd = 18;
resetTyping();
}
else {
i = text_array.length;
}
}
}
return (
<div className='container'>
<div
className="typing-test"
id="start"
onKeyDown={(e) => {
handleKey(e.key);
e.preventDefault();
}
}
tabIndex={0}
>
{text.split("").map((char: string, index: number) => {
let state = charsState[index];
let color = state === 0 ? "white" : state === 1 ? "green" : "red";
return (
<span
key={char + index}
style={{ color }}
className={currIndex + 1 === index ? "curr-letter" : ""}
>
{char}
</span>
);
})}
</div>
<h2 className='debug'> TIMER: {cd}, I: {i}, ERRORS: {err}, MULTIPLIER: {xpM}, Type XP: {correctChar * xp}, CurrXP: {correctChar * xp * xpM} XPTotal: {tXP} bonusCounter: {bonusCounter}, BONUS: {bonus}</h2>
</div>
);
}
export {tXP};
export default TypeF;
Any help would be amazing, I have been stuck on this for 2 days and it is the last bit I need to complete so I can move to the next phase.
Your child component is a function component. You can't get a ref to an instance of a function component, because there is no instance. If you really need to use a function component and also expose some custom object as a ref, then you can use the useImperativeHandle hook plus forwardRef to define what the parent component should receive on its ref. For example:
const Type = React.forwardRef((props, ref) => {
// ...
useImperativeHandle(ref, () => {
// The following object is what will get assigned to the
// parent component's this.child.current
return {
afftimer: function () {
tmr = setInterval(tock, 1000);
if (i >= text_array.length) {
clearInterval(tmr);
}
}
}
});
// ...
})
But useImperativeHandle is not a common thing to use. There is likely a more standard way to solve your problem. The normal way for a parent component to tell a child component what to do is with props, not with refs.

Using jQuery in React to modify CSS of an element

Hello,
I know its not recommended to use jQuery with react & I am aware of method on react for changing CSS of element but here I am just trying to see if my req can be achieved or not , all i want is to change the colour of li element when corresponding tick icon is clicked for it, I am using a jQuery code
const markdone = () => {
let c = $("#ll")
console.log(c)
$(c).closest("li").css("background-color", "green");
};
but when i am clicking the css gets applied but not on its corresponding li element in my case for ex have attached image when i click on 3 tick icon css gets changed for 1 is there any way i can fix it
attaching whole code below
check markdone function for making css change :
const [input, setValue] = useState("");
const [todos, setTodos] = useState([]);
// passing entered
const handleInput = (event) => {
setValue(event.target.value);
};
const lp = (event) => {
// let c = [1,2,34,55]
event.preventDefault();
// if no input nothing will happen return none
if (!input) return;
// using spread operator its used whenever we need to add array data to exiting array
const newTodos = [...todos, input];
setTodos(newTodos);
// clearing input text
setValue("");
};
const handeldel = (index) => {
// console.log(index)
todos.splice(index, 1);
setTodos([...todos]);
// const newTodos = todos.splice(index, 1);
// setTodos([...newTodos]);
};
const [line, setline] = useState(false);
// const [ll, setll] = useState(false);
const markdone = () => {
let c = $("#ll")
console.log(c)
$(c).closest("li").css("background-color", "green");
};
useEffect(() => {
$(document).ready(function() {
$("#pk").click(function(e) {
// e.preventDefault();
alert('hello')
});
});
});
return ( <
div >
<
h1 id = "pk"
className = "text-center font-weight-bolder alert-info mb-5" >
Tasks To Do < i class = "fas fa-clipboard-list text-success" > < /i> <
/h1> <
div class = "input-group mb-3 container" >
<
input className = "form-control border-primary font-weight-bold"
style = {
{
height: 60
}
}
placeholder = "Enter Text here"
type = "text"
value = {
input
}
onChange = {
handleInput
}
/> <
div class = "input-group-append" >
<
button className = "input-group-append font-weight-bolder "
style = {
{
fontSize: 20
}
}
onClick = {
lp
} >
{
" "
} <
i class = "fas fa-plus-square fa-2x p-2" > < /i>{" "} <
/button> <
/div> <
/div> {
todos.map((x, index) => ( <
ol style = {
{
listStyle: "outside"
}
}
className = "container" >
<
li className = "font-weight-bolder table-bordered text-capitalize alert-secondary "
style = {
{
fontSize: 30,
textDecoration: line ? "line-through" : "none",
// backgroundColor: ll ? "Chartreuse" : "none",
}
} >
{
x
} <
i class = "fas fa-check-circle float-md-right text-success"
id = "ll"
onClick = {
markdone
} >
< /i>{" "} <
i class = "fas fa-trash-alt text-danger float-md-right"
onClick = {
() => handeldel(index)
} >
< /i> <
/li> <
/ol>
))
}
{ /* for future ref */ } {
/* <div >
{data.map((user) => (
<div className="user">{user.id + " " + user.name
}</div>
))}
</div> */
} <
/div>
I suppose using a Ref should do the trick, as Refs provide a way to access DOM nodes or React elements created in the render method.
Just put it on the element you'd like to style using jQuery and access it with RefName.current
IDs must be unique
You do not need jQuery, just delegation
Plain JS - there are other ways in React
I am assuming .input-group-append is the container
document.querySelector(".input-group-append").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("text-success")) {
tgt.closest("li").style.backgroundColor = "green";
}
})

Object value replacing existing object value - Javascript

I'm trying to create an object with an array of multiple objects inside it, each inner-object representing a card.
I initialise all three outside of a forEach() loop, push each item into the array and then assign that array to a key in my outer-object:
const cart = {};
const cartItems = [];
const cartItem = {}
cart['cart-items'] = cartItems;
cartItems.push(cartItem);
Inside the forEach() I take the card data, every time that cards button is clicked, and assign it to the inner-object:
///forEach() with 'click' event-handler for the buttons...
if (cartItem.id !== currentCardId) {
cartItem['id'] = currentCardId;
cartItem['name'] = currentCardName;
cartItem['price'] = this.dataset.cardPrice;
cartItem['quantity'] = 1;
} else {
cartItem.quantity = cartItem.quantity + 1;
}
///...end of forEach()
This increments the 'quantity' of the 'card' if I click the same button multiple times, but when I click on a separate button it overwrites the existing card and it's 'quantity' value.
I understand if I initialise cartItem and cartItems inside the loop it prevents this overwriting, but then the cards 'quantity' doesn't increment, it just creates a separate object with a 'quantity' of '1'.
Any idea how I can work around this?
Edit
Complete code:
addCartBtn.forEach(i => {
i.addEventListener('click', function(e) {
let currentCardId = this.dataset.cardId;
let currentCardName = this.dataset.cardName;
let currentCardQuantity = 0;
let currentCardPrice;
let removeCartItem = document.getElementsByClassName('remove-cart-item');
if (cartItem.id !== currentCardId) {
cartItem['id'] = currentCardId;
cartItem['name'] = currentCardName;
cartItem['price'] = this.dataset.cardPrice;
cartItem['quantity'] = 1;
} else {
cartItem.quantity = cartItem.quantity + 1;
}
if (this.dataset.cardPrice >= 1) {
currentCardPrice = '£' + this.dataset.cardPrice;
} else {
currentCardPrice = this.dataset.cardPrice + 'p';
}
if (currentCardName.length > 10) {
currentCardName = currentCardName.substring(0, 9) + '...';
}
if (document.getElementById(`${currentCardId}`)) {
cartItems.forEach(i => {
if (currentCardId === i) {
currentCardQuantity += 1;
document.getElementById(
`${currentCardId}`
).innerHTML = `x${currentCardQuantity}`;
} else {
document.getElementById(`${currentCardId}`).innerHTML = 'x1';
}
});
} else {
dropdownCheckoutContainer.innerHTML += `<div class="dropdown-card" id="remove-${currentCardId}"><div class="dropdown-card-display"><p class="remove-${currentCardId}"><i class="fa fa-minus-square remove-cart-item" data-remove-id="${currentCardId}"></i>${currentCardName}</p></div><div class="dropdown-quantity"><p class="remove-${currentCardId}" id="${currentCardId}">x1</p></div><div class="dropdown-price"><p class="remove-${currentCardId}">${currentCardPrice}</p></div><div class="dropdown-hidden-id"><input class="remove-${currentCardId}" type="hidden" name="${currentCardId}" data-remove-id="${currentCardId}"></div></div>`;
}
if (dropdownCheckoutContainer.childElementCount >= 7) {
dropdownCheckoutContainer.style.overflow = 'scroll';
dropdownCheckoutContainer.style.borderBottom =
'1px solid rgba(255, 98, 0, 0.5)';
}
if (dropdownCheckoutContainer.childElementCount > 1) {
notificationIconContainer.style.display = 'flex';
notificationIcon.innerHTML =
dropdownCheckoutContainer.childElementCount - 1;
}
for (const i of removeCartItem) {
i.addEventListener('click', function(e) {
let btnId = this.dataset.removeId;
let currentRow = document.getElementById(`remove-${btnId}`);
let idIndexes = [];
if (dropdownCheckoutContainer.childElementCount > 1) {
dropdownCheckoutContainer.removeChild(currentRow);
}
notificationIcon.innerHTML = notificationIcon.innerText - 1;
if (!(dropdownCheckoutContainer.childElementCount >= 7)) {
dropdownCheckoutContainer.style.borderBottom = 'none';
if (checkoutFull.childElementCount === 1) {
checkoutFull.innerHTML = '';
}
}
cartItems.forEach(i => {
if (i === btnId) {
idIndexes.push(cartItems.indexOf(i));
}
});
for (let i = idIndexes.length - 1; i >= 0; i--) {
cartItems.splice(idIndexes[i], 1);
}
});
i.addEventListener('mouseup', () => {
if (dropdownCheckoutContainer.childElementCount <= 2) {
document.getElementById('empty-cart').style.display = 'block';
checkoutLink.classList.add('checkout-link-disabled');
}
if (dropdownCheckoutContainer.childElementCount <= 2) {
notificationIconContainer.style.display = 'none';
}
});
}
console.log(cart);
});
i.addEventListener('mouseup', () => {
document.getElementById('empty-cart').style.display = 'none';
checkoutLink.removeAttribute('class', 'checkout-link-disabled');
});
});
suppose, You have a data like that
let cart = { 'cart-items': [{id: 1, name: 'test 1', price: 30.9, quantity: 1}] }
When You are going to click on button then currentCardId = 1
Then you need to the following at click event.
const existsIndex = cart['cart-items'].findIndex((item) => item.id === currentCardId )
if (existsIndex !== -1) {
cart['cart-items'][existsIndex].quantity++
} else {
cart['cart-items'].push({id: currentCardId, name: 'sadsad', quantity: 1})
}

Categories