I am currently learning React JS and want to convert one of my vanilla JS projects into React. However, I do not know convert functions using JS DOM functions (I know you should not use this in React) into more REACT JS appropriate function.
function getRandom(letters) {
var randomSet = letters[Math.floor(Math.random() * letters.length)];
//console.log("set random", randomSet);
document.getElementById("demo3").innerHTML = randomSet;
_timer = setTimeout(() => getRandom(letters), 1000);
}
Thanks for the help everyone!
CodePudding user response:
I would probably do something like this.
import React, { useEffect, useState } from 'react';
const Component = () => {
const [randomLetter, setRandomLetter] = useState();
const getRandomLetters = (letters) => {
const randomSet = letters[Math.floor(Math.random() * letters.length)];
setRandomLetter(randomSet);
}
useEffect(() => {
const letters = ['a', 'b', 'c'];
const randomLetterInterval = setInterval(() => {
getRandomLetters(letters)
}, 1000);
return () => {
clearInterval(randomLetterInterval);
}
}, []);
return (
<>{randomLetter}</>
);
};
CodePudding user response:
import React from "react";
import { render } from "react-dom";
class MyFirstComponent extends React.Component {
constructor(props) {
super(props);
this.state = { rndNum: null, offOn: true };
}
componentDidMount() {
this.getRandom("Hello-React");
}
getRandom = (letters) => {
var randomSet = letters[Math.floor(Math.random() * letters.length)];
//console.log("set random", randomSet);
this.setState({ rndNum: randomSet });
// document.getElementById("demo3").innerHTML = randomSet;
if (this.state.offOn) {
setTimeout(() => this.getRandom(letters), 1000);
}
};
OffOn = () => {
this.setState({ offOn: !this.state.offOn });
if (!this.state.offOn) {
this.getRandom("Hello-React");
}
};
render() {
return (
<div>
<h2>{this.state.rndNum}</h2>
<button onClick={this.OffOn}>Start/Stop</button>
</div>
);
}
}
render(<MyFirstComponent />, document.getElementById("root"));
CodePudding user response:
In React state informs how a component is rendered. When the state changes, a new render is performed.
At least one state for the updated random letter. In this example I've also added a state for the array of letters I'm passing into the function.
Using
useEffect
to call the randomise function with asetTimeout
when the component is initially rendered.getRandom
sets a new state for the letter, the component renders again, and that letter is displayed.
const { useEffect, useState } = React;
function Example({ data }) {
// Initialise the states
const [ letters, setLetters ] = useState(data);
const [ letter, setLetter ] = useState('Waiting for random letter');
// Set the new state with a random letter
function getRandom() {
const rnd = Math.floor(Math.random() * letters.length);
setLetter(letters[rnd]);
}
// Use a useEffect to call the function
// on the first render
useEffect(() => {
const timer = setTimeout(getRandom, 1000);
return () => clearTimeout(timer);
}, []);
return (
<div>
<p>{letter}</p>
</div>
);
}
// Just creating an array of letters
const arr = Array.from(Array(26)).map((e, i) => i 65);
const letters = arr.map((x) => String.fromCharCode(x));
// Passing in that array as a component prop
ReactDOM.render(
<Example data={letters} />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>