Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
Webpack - React, How to pass data from script tag

I have embeddable react widget with webpack config, below is the script tag which will be embedded in the client side.

<script>
    (function (w, d, s, o, f, js, fjs) {
        w['simple-widget'] = o; w[o] = w[o] || function () { (w[o].q = w[o].q || []).push(arguments) };
        js = d.createElement(s), fjs = d.getElementsByTagName(s)[0];
        js.id = o; js.src = f; js.async = 1; fjs.parentNode.insertBefore(js, fjs);
    }(window, document, 'script', 'w1', 'widget.js'));
    w1('init', { targetElementId: 'simple-widget', message: "some string" });

</script>

How to capture

message: "some string"

and send it to react ?

Below is my code to apiHandle

function apiHandler(api, params) {
    if (!api) throw Error("API method required");
    api = api.toLowerCase();

    let config = window[widgetConfigName];

    switch (api) {
        case "init":
            config = Object.assign({}, config, params);
            window[widgetConfigName] = config;

             // get a reference to the created widget component so we can
            // call methods as needed
            widgetComponent = React.createRef();
            ReactDOM.render(
           <Widget ref={widgetComponent} />,
               document.getElementById(config.targetElementId)
           );
       break;
      case "message":
          console.log("switch case message");
          // Send the message to the current widget instance
          widgetComponent.current.setMessage(params);
          break;
      default:
          throw Error(`Method ${api} is not supported`);
    }
}

Below is my react Wideget.js Component

class Widget extends React.Component {
    constructor(props) {
    super(props);
         this.state = {
            message: null,
        };
    }

render() {
    console.log(this.state);
    return (
        <div className="main_container">
            {message}
        </div>
    );
}
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can get the message property from the simple-widget element if it exists in your DOM elements.

class Widget extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: null,
    };
  }
  
  componentDidMount() {
    const widgetElement = document.getElementById('simple-widget');
    this.setState({message: widgetEelement.message})
  }

  render() {
    return (
      <div className="main_container">
        {message}
      </div>
   );
  }
}

Explanation

In the component did mount function, you can get the widget by its id and get the message property from it, then set this message to the state.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda