This one is hard one. I spent some days now to solve this issue but all the solutions I tried wasn't accurate.
The thing is that I'm trying to build 'typing text effect'. This should also handle change of the sentences, ie. the first sentence is typed, then it disappears and the other sentences is starting to be typed again, and so on, it goes in the loop. The issue here is that while the first sentence is finished I would like to leave my blinker for a while, for example for 2 sec. This seems to be a perfect place to use setTimeout but all of my trials were unfortunately wrong.
I would really appreciate if you could help me! Thank you
Here's my code:
import React, { Component } from 'react';
import '../../sass/main.scss';
class TypeAnimation extends Component {
constructor(props) {
super(props);
this.state = {
sec: 0,
sec2: 0,
currentSentence: 0,
blinker: '|',
};
}
componentDidMount() {
this.textInterval = setInterval(() => {
this.setState(
prevState => ({
sec: prevState.sec !== this.props.text[0].length ? prevState.sec + 1 : 0,
currentSentence: prevState.sec === this.props.text[0].length ?
prevState.currentSentence + 1 : prevState.currentSentence,
})
);
}, 100);
}
render() {
let otherSentences;
const nextSentences = this.props.text; // here comes the array of few sentences
const currentText = nextSentences[this.state.currentSentence];
if (this.state.currentSentence !== nextSentences.length) {
otherSentences = currentText.substr(0, this.state.sec);
} else {
clearInterval(this.textInterval);
otherSentences = nextSentences[nextSentences.length - 1];
}
return (
<div>
<h2>
{otherSentences}
<span className='blinker'> {this.state.blinker} </span>
</h2>
</div>
);
}
}
export default TypeAnimation;
Related
I'd like some help understanding why my React Component isn't working. I'm trying work on my React/Js fundamentals by making a basic timer. The component is rendering great, just nothing is happening. I'm looking at the React Profiler on Chrome and my variables seem to be updating correctly.
I know it's basic, I'd just rather start and fix my mistakes and learn on the way.
Any help whatsoever would be greatly appreciated!
import React from 'react'
var sec = 0;
var min = 0;
var hrs = 0;
var timer_id;
// Helper Functions
function tick(){
sec++;
if (sec >= 60){
sec = 0;
min ++;
if (min >= 60){
min = 0;
hrs++;
};
};
}
function add(){
tick();
timer();
}
function timer(){
console.log("TIMER");
timer_id = setTimeout(add, 1000);
}
// Clock Component
class Clock extends React.Component{
render(){
timer();
return (
<div className="clock-face">
<h4> {hrs} : {min} : {sec}</h4>
<button
onClick = {() => clearTimeout(timer_id)}> Stop </button>
</div>
);
}
}
export default Clock;
React components only get rerendered when their props or state changes (or when forced to rerender, but we don't do that). You're updating hrs/min/sec in global variables; those aren't tracked by React.
In addition, it's not a good idea to have render() execute a side effect (timer() in your case); React may elect to render your function more than once.
Here's an example of your clock as a class component that ticks along and cleans the timer up after it's unmounted.
The magic that causes the rerendering here is this.setState being called.
import React from "react";
function divmod(a, b) {
return [Math.floor(a / b), a % b];
}
class Clock extends React.Component {
state = { time: 0 };
componentDidMount() {
this.timer = setInterval(this.tick, 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
tick = () => {
this.setState(({ time }) => ({ time: time + 1 }));
};
render() {
const { time } = this.state;
const [hmins, secs] = divmod(time, 60);
const [hrs, mins] = divmod(hmins, 60);
return (
<div className="clock-face">
<h4>
{" "}
{hrs} : {mins} : {secs}
</h4>
</div>
);
}
}
Ok, so first time question-asker here, but I'm having trouble rendering a class to a grid cell, then removing it. The idea is the grid is the floor, and the class represents a roomba moving around it. I want to render the roomba where the cell id matches the position saved in state. Here's my code for the grid component:
import React, { useState, useEffect } from "react";
function Grid(props) {
const [position, setPosition] = useState(props.location);
const [roomba, setRoomba] = useState({
location: "1, 1",
});
const theRoomba = `${position[0]}, ${position[1]}`;
const renderRoomba = document.getElementById(theRoomba);
useEffect(() => {
if (roomba) {
setPosition(props.location);
setRoomba(position);
console.log("Im the current location", props.location);
}
}, [props.location]);
const grid = [];
for (let i = 10; i >= 1; i--) {
for (let j = 10; j >= 1; j--) {
grid.push(
<div className="square" id={`${i}, ${j}`} key={`${i}, ${j}`}>
{`${i}, ${j}`}
</div>
);
}
}
const updatedGrid = [];
grid.map((cell) => {
if (renderRoomba) {
renderRoomba.classList.add("roomba");
updatedGrid.push(cell);
} else {
updatedGrid.push(cell);
}
return updatedGrid;
});
return <div className="grid">{updatedGrid}</div>;
}
export default Grid;
I'm a bit of a noob and know this is probably bloated, but it currently renders my 10x10 grid, and I can move my roomba around but can't ever remove the className='roomba' from the previous cell. I've tried a few DOM manipulation methods but nothing seems very 'React-ty'. Appreciate any help/feedback, this has been wracking my brain all week!
I'm new to learning React and Gatsby, and am trying to find the best way to apply simple a Javascript animation to a DOM element within a component. I know how to handle component events with onClick etc, but say for example I want to continuously change the colour of a <span> in my Header.js component every 2 seconds.
import React from 'react';
export default function Header() {
return (
<header>
<p>This is a <span>test!</span></p>
</header>
)
}
I'd then want to use some JS like:
const spanEl = document.querySelector('header span');
let counter = 0;
const changeColor = () => {
if (counter % 2 == 0) {
spanEl.style.color = "red";
} else {
spanEl.style.color = "blue";
}
counter++;
if (counter == 10) counter = 0;
}
setInterval(changeColor, 2000);
I found that I could put this inside a script tag in html.js before the closing body tag, but is there a way to keep this functionality within the component? Do I need to completely rethink my approach when working within this framework?
If you want to approach this with idiomatic React, then I would recommend expressing this behavior using hooks, component lifecycles, and effects.
The official React docs for hooks and effects are very good, I would start there.
import React from 'react';
const noop = () => null;
// Encapsulate the interval behavior
const useInterval = (callback, delay) => {
const savedCallback = useRef(noop);
useEffect(() => {
savedCallback.current = callback;
savedCallback.current();
}, [callback]);
useEffect(() => {
const id = setInterval(savedCallback.current, delay);
return () => clearInterval(id);
}, [delay]);
};
export default function Header() {
const [color, setColor] = useState("blue");
// setColor causes a re-render of the component
const updateColor = setColor(color === "blue" ? "red" : "blue");
useInterval(updateColor, 2000);
// Use the jsx to change the color instead of reaching into the dom
return (
<header>
<p>This is a <span style={{ color }}>test!</span></p>
</header>
)
}
[EDIT: I've just seen the answer from #windowsill, which I think is better than mine; I would recommend going with that solution.]
In a React functional component, you need to use the useReference hook to target an element (rather than selecting it with document.querySelector()) and the useEffecet hook to set and clear the timeout when the component mounts/unmounts:
import React, {
useEffect,
useRef,
useCallback
} from 'react';
export function Header() {
const animatedText = useRef(null);
const runAnimation = useCallback(elem => {
const currColour = elem.style.color;
elem.style.color = (currColour === 'red' && 'blue') || 'red';
}, []);
useEffect(() => {
const animationInterval = setInterval(() => {
runAnimation(animatedText.current);
}, 2000);
return () => {
clearInterval(animationInterval);
}
}, [runAnimation]);
return (
<header>
<p>This is a <span ref={animatedText}>test!</span></p>
</header>
);
}
The useCallback hook is used for optimization purposes and prevent the function runAnimation from being re-defined and initialized every time the component re-renders.
I'm a newbie in React. I have 6 divs and whenever I call foo() I want to add a number to the first div that's empty.
For example, let's say that the values of the six divs are 1,2,0,0,0,0 and when I call foo(), I want to have 1,2,3,0,0,0.
Here is what I've tried:
var index = 1;
function foo() {
let var x = document.getElementsByClassName("square") // square is the class of my div
x[index-1].innerHTML = index.toString()
index++;
}
I don't know when I should call foo(), and I don't know how should I write foo().
The "React way" is to think about this is:
What should the UI look like for the given data?
How to update the data?
Converting your problem description to this kind of thinking, we would start with an array with six values. For each of these values we are going to render a div:
const data = [0,0,0,0,0,0];
function MyComponent() {
return (
<div>
{data.map((value, i) => <div key={i}>{value}</div>)}
</div>
);
}
ReactDOM.render(<MyComponent />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Now that we can render the data, how are we going to change it? From your description it sounds like every time a function is called, you want change the first 0 value in the array to another value. This can easily be done with:
// Find the index of the first 0 value
const index = data.indexOf(0);
if (index > -1) {
// if it exists, update the value
data[index] = index + 1;
}
To make this work properly with React we have to do two things: Keep track of the updated data in state, so that React rerenders the component when it changes, and update the data in a way that creates a new array instead of mutating the existing array.
You are not explaining how/when the function is called, so I'm going to add a button that would trigger such a function. If the function is triggered differently then the component needs to be adjusted accordingly of course.
function update(data) {
const index = data.indexOf(0);
if (index > -1) {
data = Array.from(data); // create a copy of the array
data[index] = index + 1;
return data;
}
return data;
}
function MyComponent() {
var [data, setData] = React.useState([0,0,0,0,0,0]);
return (
<div>
{data.map((value, i) => <div key={i}>{value}</div>)}
<button onClick={() => setData(update(data))}>Update</button>
</div>
);
}
ReactDOM.render(<MyComponent />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
You would use state to hold the value and then display the value of that variable.
If you're using functional components:
const App = () => {
const [values, setValues] = React.useState([0, 0, 0, 0, 0, 0]);
const [index, setIndex] = React.useState(0);
const foo = () => {
const tempValues = [...values];
tempValues[index] = index;
setValues(tempValues);
setIndex((index + 1) % values.length);
}
return (
<div>
{ values.map((value) => <div key={`square-${value}`}>{value}</div>) }
<button onClick={ foo }>Click me</button>
</div>
);
};
In class-based components:
constructor(props) {
super(props);
this.state = {
values: [0, 0, 0, 0, 0, 0],
index: 0
};
this.foo = this.foo.bind(this);
}
foo() {
const tempValues = [...values];
const newIndex = index + 1;
tempValues[newIndex] = newIndex;
this.setState({
values: tempValues,
index: newIndex
});
}
render() {
return (
<div>
{ values.map((value) => <div key={`square-${value}`>value</div>) }
<button onClick={ this.foo}>Click me</button>
</div>
);
}
If you need to set the innerHTML of a React component, you can try this:
return <div dangerouslySetInnerHTML={foo()} />;
the foo() here returns the value you want to post in the div.
But in my opinion, your way of thinking on this problem is wrong.
React is cool, but the logic is a bit different of common programming :D
The ideal approach would be to have the divs created by React (using its render method). Then you can pass a variable from array, which is stored in your state. You then just need to change this array within the state and it'll reflect in your view. If you need a working example, just let me know.
However, if you want to update the divs that are not created using react, then you need to use a dirty approach. I would suggest not to use react if you can't generate the view from react.
React is good to separate the concerns between the view and the data.
So the concept of state for this example is useful to store the data.
And the JSX, the React "template" language, to display the view.
I propose this solution:
import React from "react";
class Boxes extends React.Component {
state = {
divs: [1, 2, 3, 0, 0, 0]
};
add() {
// get the index of the first element equals to the condition
const index = this.state.divs.findIndex(elt => elt === 0);
// clone the array (best practice)
const newArray = [...this.state.divs];
// splice, i.e. remove the element at index AND add the new character
newArray.splice(index, 1, "X");
// update the state
// this is responsible, under the hood, to call the render method
this.setState({ divs: newArray });
}
render() {
return (
<div>
<h1>Boxes</h1>
{/* iterate over the state.divs array */}
{this.state.divs.map(function(elt, index) {
return (
<div
key={index}
style={{ border: "1px solid gray", marginBottom: 10 }}
>
{elt}
</div>
);
})}
<button onClick={() => this.add()}>Add a value</button>
</div>
);
}
}
export default Boxes;
So, first of all, what I'm trying to do is the following: I have a few divs that contain some text and an image. All the data for the divs is stored in a state array. You can also add divs and delete whichever div you desire. What I would like to implement now, is to change the picture when the user clicks on an image. There is a preset image library and whenever the user clicks on the image, the next image should be displayed.
Here is some relevant code:
let clicks = 0;
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
data : [
createData( someimage, "Image 1"),
createData( anotherimage, "Image 2"),
createData( thirdimage, "Image 3"),
createData( fourthimage, "Image 4"),
],
imgs : [imgsrc1,imgsrc2, imgsrc3, imgsrc4],
}
}
newIcon (n) {
let newStateArray = this.state.data.slice();
let newSubStateArray = newStateArray[n].slice();
if(clicks === 1) {
newSubStateArray[0] = this.state.imgs[0];
this.setState({imgsrc:newSubStateArray});
clicks++;
} else if (clicks === 2) {
newSubStateArray[0] = this.state.imgs[1];
this.setState({imgsrc:newSubStateArray});
clicks++;
} else if (clicks === 3) {
newSubStateArray[0] = this.state.imgs[2];
this.setState({imgsrc:newSubStateArray});
clicks++;
} else if (clicks === 4) {
newSubStateArray[0] = this.state.imgs[4];
this.setState({imgscr:newSubStateArray});
clicks++;
}
}
render () {
let { data }= this.state;
return(
<div>
{data.map((n) => {
return(
<Child imgsrc={n.imgsrc} key={n} newIcon={this.newIcon.bind(this, n)} header={n.header} />
);
})}
</div>
);
}
A few sidenotes: createArray is a function to create the sub-arrays and can probably be ignored for this question. What is important to know is, that the first element is called imgsrc, and the second element is called
So, something is going wrong here but I'm not sure what it is exactly. My guess is, that I'm not properly accessing the values within the arrays. Above, you can see that I tried to slice the arrays and to then allocate the new value. Another problem I've encountered, is that n comes up as undefined, when I try to call it from my newIcon()-function.
I'm kind of lost here, as I'm quite new to React so any sort of hints and suggestions are welcome.
I would do away with all that code in newIcon, and keep clicks as part of the state. If you have an array of images then you can use clicks as a pointer to the next image that should be shown.
In this example I've taken the liberty of adding in dummy images to help explain, and changed clicks to pointer as it makes more sense.
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
// clicks is called `pointer` here and initially
// is set to the first index of the imgs array
pointer: 0,
imgs: [
'https://dummyimage.com/100x100/000000/fff.png',
'https://dummyimage.com/100x100/41578a/fff.png',
'https://dummyimage.com/100x100/8a4242/fff.png',
'https://dummyimage.com/100x100/428a49/fff.png'
]
};
// Bind your class method in the constructor
this.handleClick = this.handleClick.bind(this);
}
// Here we get the length of the imgs array, and the current
// pointer position. If the pointer is at the end of the array
// set it back to zero, otherwise increase it by one.
handleClick() {
const { length } = this.state.imgs;
const { pointer } = this.state;
const newPointer = pointer === length - 1 ? 0 : pointer + 1;
this.setState({ pointer: newPointer });
}
render() {
const { pointer, imgs } = this.state;
// Have one image element to render. Every time the state is
// changed the src of the image will change too.
return (
<div>
<img src={imgs[pointer]} onClick={this.handleClick} />
</div>
);
}
}
DEMO
EDIT: Because you have more than one div with images the sources of which need to change, perhaps keep an array of images in a parent component and just pass a subset of those images down to each Image component as props which you then store in each component's state. That way you don't really need to change the Image component that much.
class Image extends React.Component {
constructor(props) {
super(props);
this.state = { pointer: 0, imgs: props.imgs };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const { length } = this.state.imgs;
const { pointer } = this.state;
const newPointer = pointer === length - 1 ? 0 : pointer + 1;
this.setState({ pointer: newPointer });
}
render() {
const { pointer, imgs } = this.state;
return (
<div>
<img src={imgs[pointer]} onClick={this.handleClick} />
</div>
);
}
}
class ImageSet extends React.Component {
constructor() {
super();
this.state = {
imgs: [
'https://dummyimage.com/100x100/000000/fff.png',
'https://dummyimage.com/100x100/41578a/fff.png',
'https://dummyimage.com/100x100/8a4242/fff.png',
'https://dummyimage.com/100x100/428a49/fff.png',
'https://dummyimage.com/100x100/bd86bd/fff.png',
'https://dummyimage.com/100x100/68b37c/fff.png',
'https://dummyimage.com/100x100/c9a7c8/000000.png',
'https://dummyimage.com/100x100/c7bfa7/000000.png'
]
}
}
render() {
const { imgs } = this.state;
return (
<div>
<Image imgs={imgs.slice(0, 4)} />
<Image imgs={imgs.slice(4, 8)} />
</div>
)
}
}
DEMO
Hope that helps.
Try to bind the newIcon() method in the constructor, like this :
this.newIcon = this.newIcon.bind(this);
and in the render method call it normally without any bind :
this.newIcon(n)