Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
Converting Javascript DOM function into REACT JS

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!

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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}</>
  );
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

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"));

Sample

about 4 years ago · Juan Pablo Isaza Denunciar

0

In React state informs how a component is rendered. When the state changes, a new render is performed.

  1. 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.

  2. Using useEffect to call the randomise function with a setTimeout when the component is initially rendered.

  3. 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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda