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

123
Vistas
How to access state / functions outside of react component

I'm trying to implement the strategy design pattern to dynamically change how I handle mouse events in a react component.

My component:

export default class PathfindingVisualizer extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            grid: [],
            mouseLeftDown: false,
        };
        const mouseStrat2 = null;     // Object I will change that has different functions for handling events
    }

    componentDidMount() {
        this.resetGrid();
        this.mouseStrat2 = new StartEndStrat();
    }

    render() {
        //buttons that change the object i want handling mouse events
    <button onClick={() => this.mouseStrat2 = new StartEndStrat(this)}>startendstrat</button>
    <button onClick={() => this.mouseStrat2 = new WallStrat(this)}>wallstrat</button>
    }
}

I want my mouse strats that will access change the component with differing methods to handle mouse events

export class StartEndStrat {
    handleMouseDown(row, col) {
        // I want to access component state and call functions of the component
        this.setState({ mouseLeftDown: true });
        PathfindingVisualizer.resetGrid();
    }
    //other functions to change other stuff

    handleMouseEnter(row, col) {
        console.log('start end strat');
    }
}

export class WallStrat {
    handleMouseDown(row, col) {
        this.setState({ mouseLeftDown: true });
    }

    handleMouseEnter(row, col) {
        console.log('wallstrat');
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can try use Refs to do this.

refOfComponent.setState({ ... })

But I would rather recommend you to avoid such constructions as this may add complexity to your codebase.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Solution I found was to use a ref callback to make the DOM element a global variable.

<MyComponent ref={(MyComponent) => window.MyComponent = MyComponent})/>

Then you can access MyComponent with window.MyComponent, functions with window.MyComponent.method() or state variables with window.MyComponent.state.MyVar

My App.js:


function App() {
  return (
    <div className="App">
      <PathfindingVisualizer ref={(PathfindingVisualizer) => {window.PathfindingVisualizer = PathfindingVisualizer}} />
      
    </div>
  );
}

Other.js:

handleMouseDown() {
    window.PathfindingVisualizer.setState({mouseLeftDown: true});
}
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