4

We are moving towards a hybrid-headless model with Drupal 7. All our data is exposed through RESTful and I have successfully built React app using the data.

How can pull that app in as a block? I put the code in a block and the app loses much of its styling and 1 third of the data is hidden. The basic functionality still works, but that's not enough.

Is there some trick to getting the a the full app to run correctly in a block?

Thank you

3

I solved this as follows:

  1. install react-app-rewired: npm i --D react-app-rewired -- this is important so you don't try to load react more than once

  2. change package.json so build executes react-app-rewired build -- full instructions here: https://github.com/timarney/react-app-rewired

  3. Pick a spot in your Drupal install for your react app -- I chose sites/all/react, it seemed right to me

  4. load react into your template using the CDN links https://reactjs.org/docs/cdn-links.html

  5. update package.json with homepage for your app to reflect where you are saving it for example: "homepage": "/sites/all/libraries/myapp/",

  6. build your react app and copy the contents of the build folder to the location you chose for storing your app

  7. build a simple module to load your app as a block (code below)
  8. add the block to your page however you see fit
/* Adds the block to the block menu */
function my_app_block_info() {
  $blocks['my_react_app'] = array( //a new array for each new app
    'info' => t('My React App'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/* set the content for the block */

function my_app_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'my_react_app': //a new case for each new app 
        $block['content'] = file_get_contents(libraries_get_path('appfolder').'/index.html');

        break;
     }
  return $block;
}
 /* 
   file_get_contents loads the index.html page that loads 
   the react app don't use libraries_get_path if you saved your app 
   somewhere else
 */
  • Did you try PDB @daniel-lefebvre – kalidasan Jan 16 at 12:38
  • Nice module, thanks :) But I am working with D7 so, there are a number of nice headless options that I don't have access to. – Daniel Lefebvre Jan 16 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.