Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

GIFT AKARIS
GIFT AKARIS
4,383 Points

How do I use react as a front-end template engine with express ?

How do I use react as a front-end template engine with express ?

1 Answer

hey GIFT AKARIS you would first create your routes in express, after you would have to call your api calls from the front end in react, you can use axios for this which really does the heavy lifting using promises. So your project tree could look like this

backend

  • routes
  • models
  • frontend -- react api calls

let me know if this helps

GIFT AKARIS
GIFT AKARIS
4,383 Points

Thank you Fernando,

Lets assume am using create-react-app for the front-end. How to connect the front-end and the back-end, considering the fact that create-react-app creates a package.json file?

your main project directory is your backend, that holds your json package for express, etc, then inside you would run create-react-app which creates the front end directory, inside you create your react front end ui, components etc. Then to hook up the front end to backned you would have to call the a directory that you would store the the frontend api methods.

So if a user clicks on registerUser button. That would be a method inside the react component that would call the api method inside the api directoy which then calls the backend end api

frontend react

import axios from "axios";

// Register User
export const registerUser = userData  => {
  axios
    .post("/api/users/register", userData)
    .then(res => console.log(res.data))
    .catch(err =>
      dispatch({
        type: err,
        payload: err.response.data
      })
    );
};

backend express

router.post("/register", (req, res) => {

  // Check Validation
const newUser = new User({
   name: req.body.name,
   email: req.body.email,
   password: req.body.password
      });
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
    }
  });
});