3. React with simple api

Agata Krzywda
2 min readMar 22, 2017

--

This is the third part of my React tutorials. See Intro to react.js here

Let’s get started with simple example to use api with react.

First what we need to do it:

1. Set initial state

As we can see our state is a object with two properties term and img

  • term to store current value which we passing to input
  • img to store url which late we will passing to <img src={url}/>

2. Input with value and onChange method

  • value takes what is stored in our state as term
  • onChange is a function which changes our state depending on the current input value. To change state we need to use the this.setState() method which also triggers UI update.

3. Form with handleSubmit method

Now we need to wrap our input field inside a form together with an add button.

  • handleSubmit is a function which does three things:
  1. Cleans the input field after a submit action is triggered, by resetting term to the initial empty string value
  2. Fetch a data from giphy api using fetch method with promises which is very simple to use. You also can use axios. Great articles about axios here and here
  • first you need resolve with json (what is very important)
  • then you have your access to json data which you can use to update state
  • last thing is catch error

3. The preventDefault() method stops the default action of an element from happening

4. Show result on the screen

Inside render method below form we passing <img /> where we are passing state img and also alt element with current term value

<img src={this.state.img} height="200" alt={this.state.term} />

And we are done ;)

Code at github

Now is your turn, try do it by your own.

Enjoy;)

Next tutorial Four ways to style react components

--

--