React and AJAX: Super Quick Simple Example

Say you needed to make a quick prototype in React and AJAX to populate your React component with some JSON. How you would you do it?┬áThat’s my current adventure in exploring React and how to use it. The simplest way is to make your calls in the root component and send the state down into the other components through props. Here’s a super quick example:

In this example, the root component, once it’s loaded, it sends off an Ajax request for data from a server. Once that returns, it updates the component’s state, which passes that data through props of another component. The cool thing is, whenever that state updates, through clicks or whatever, you don’t have to do anything to update the display. I come from the old school background of plain old javascript and jquery, so this is pretty magical. I’m totally excited to see what else React can do.

This works as long as your React component is simple. For bigger applications, where there are multiple React components nested within each other, ]multiple sources generating events, and multiple endpoints for AJAX calls, this could get messy and hard to understand which component is making what call. Plus, this isn’t exactly the most reusable React component ever written, but there’s probably a way to do it. I mean that’s the whole game of React: make super reusable and independent components for your UI. There must be a way to separate React and Ajax so that the components don’t have to know about where the data is coming from.

Check out these article for more info on several different approaches on how to make AJAX calls in your React components:

Leave a Reply

Your email address will not be published. Required fields are marked *