Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using React with ejs?

I have a front-end that is built using React states that is meant to adapt based on user action. However, my front-end React is also meant to show and allow manipulation of my server-side data. Currently my view engine is EJS, and I am using it to display data. As a broad example:

  return (<div class="col-md-6 col-sm-6 col-xs-7">
    <ul>
      <li><span class="point">Name:</span> <%= user.profile.name %> </li>
      <li><span class="point">Email:</span> <%= user.email %> </li>
    </ul>
  </div>); 

I have established that I cannot mix these ejs <%= tags with React. This makes manipulating the data a challenge. Unless I redo my UI in jQuery, I'm not sure how to proceed.

I have looked at this React documentation for passing data, but upon testing it the result does not allow me to make cross-origin calls, and my MongoDB is stored on MongoLab. Thus, I am relegated to using EJS to call my data.

With the restrictions of using React with EJS, I am puzzled over what solutions I have to implement a UI tool like React with server-side data.

like image 644
Jason Chen Avatar asked Sep 05 '16 19:09

Jason Chen


People also ask

Can I use React and EJS together?

ejs; To have a react component you would need to change the extension to app. jsx as an entry point, It worked for me...

Should I use React or EJS?

More ease with logicWhile ejs does allow javascript logics (like else-if conditioning or for loops), the syntax is both cumbersome to write and a pain to read. React introduces the JSX syntax, which while maintaining the proximity to traditional HTML, elucidates the use of programming logic to a great extent.

Do developers still use EJS?

Nowadays most dynamic sites use client-side rendering using libraries/frameworks like React, Vue, Angular, etc. We use EJS for rendering HTML emails, and HTML for PDF reports. If you want to create server side rendered views you could also use next. js which is framework using React as a templating language.

Does EJS support JavaScript?

EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.


1 Answers

In express:

res.render('view', {user: myUser});

In EJS before the app's js bundle:

<script type='text/javascript'>
  var userFromServer =<%-JSON.stringify(user)%>
</script>

Use userFromServer in your react code.

like image 140
Igorsvee Avatar answered Oct 13 '22 11:10

Igorsvee