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

114
Vistas
Passing data into a React component within existing app

I have an existing PHP app which manages products. Each products can have multiple images. Currently the process of adding or removing images is all handled via PHP server side and therefore requires a page load on each action.

As this is a large existing app I'm looking to make improvements throughout and one of these is replacing this image adding/removing section with a react component.

So, I've done exactly that. I've created a component called ImageManager and rendered it into a div with an id.

editProduct.html.twig

<div id="image-manager" data-js-images="{images: ['1.jpg', '2.jpg', '3.jpg']}"></div>

app.js

// Grab element & props
const element = document.getElementById('image-manager');
const props = element.dataset;

// Render it
ReactDOM.render(<ImageManager {...props} />, element);

Simple stuff so far. Here's my component... ImageManager.js

import React, {Fragment, useState, useEffect} from 'react';

const ImageManager = ({jsImages}) => {

    const [images, setImages] = useState([]);

    // When jsImages changes
    useEffect(() => {
        setImages(jsImages);
    }, [jsImages]);

    return (
        <Fragment>
            <div className="row">
                {images.map((img, idx) => {
                    return (
                        <div key={idx} className="col-2">
                            <img src={img}/>

                            <button type="button" className="btn btn-danger" onClick={() => {
                                // Remove it
                                const imagesCopy = [...images];
                                imagesCopy.splice(idx, 1);
                                setImages(imagesCopy);
                            }}>Remove</button>
                        </div>
                    );
                })}
            </div>
        </Fragment>
    );
};

export default ImageManager;

This all works great, however... the problem I'm having is that new images are added and handled outside of this component by some regular non-react JS. There's a button elsewhere no the page that handles the image upload and returns the new filename from the server.

So my question is, how do I let my ImageManager component know that there's a new image? It seems that changing the "data-js-images" attribute isn't picked up by the component. I'm guessing that this is only read once and if updated then nothing happens.

If I re-render the component and just merge in my new image then pass that to the "data-js-images" attribute then it works fine, but I feel re-rendering an entire components isn't the "right" way of doing this?

Just to be clear, there is no top level component or anything like that. There's just an app.js file and a bunch of HTML.

Any help would be greatly appreciated! Thanks

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

0

The useEffect hook isn't used here, because you only render the component once and dont change the props. You should watch the html element with the data attribute and when it changes you should update the components props.

You could use the MutationObserver constructor with that e.g.

const observer = new MutationObserver((mutations, observer) => {
    // Do something when the element changes
});

observer.observe(element, {
    attributes: true
});

Haven't tested it myself but it should work. Else have a look at this atricle

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