Neeraj Verma
Neeraj Verma

Reputation: 2294

React js render functional html with json response

i have created dropdown component like

  const CONTACTS_LIST = () => (

    <select>
    {
    list_data &&
    list_data .map((h, i) => 
    (
    <option key={i} value={h.list_id}>{h.name}</option>))
    }
    </select>

  );

can it be possible to render html with json response like this ?. i can set reponse in constants using setstate . but just wanted to know that is it also possible ?

    const CONTACTS_LIST = () => (

      fetch(URL)
      .then(response => response.json())
      .then(json => {
      (
        render '
        (   <select>
        {
        json &&
        json.map((h, i) => 
        (
        <option key={i} value={h.list_id}>{h.name}</option>))
        }
        </select>
        )

        )
    );

please suggest

Upvotes: 0

Views: 261

Answers (2)

freakomonk
freakomonk

Reputation: 614

You can pass the json response as a prop to the component to be rendered.

fetch(URL)
      .then(response => response.json())
      .then(
          <Component data={response} />
      )

Having html code in the then block kind of defeats React's purpose.

Upvotes: 0

Jorge Mart&#237;nez
Jorge Mart&#237;nez

Reputation: 156

Asynchronous requests are recommended to be made within the componentDidMount method, with the data you get from the api update the status of the component, when updating the status the component will be re-rendered and it will be verified if it has elements, if it has then the options of the . I hope it helps you.

class MyComponent{
  constructor () {
    super();

    this.state = {
      list_data: []
    };
  }

  componentDidMount () {
    const URL = "";
    fetch(URL).then(response => response.json())
      .then(json => {
        this.setState({
          list_data: json
        });
      });
  }

  render () {
    return (
      <select>
        {
          list_data.length === 0
            ? <option value="">Waiting moment</option>
            : list_data.map(({ h, i }) => (
              <option key={i} value={h.list_id}>{h.name}</option>
            ))
        }
      </select>
    )
  }
}

if you are using react 16 you can use the Hooks, useState and useEffect, try it this way

import React, { useEffect, useState } from 'react';

function myComponent () {
  const [list_data, set_list_data] = useState([]);

  useEffect(() => {
    const URL = "";
    fetch(URL).then(response => response.json())
      .then(json => {
        set_list_data(json);
      });
  }, []);

  return (
    <select>
      {
          list_data.length === 0
            ? <option value="">Waiting moment</option>
            : list_data.map(({ h, i }) => (
              <option key={i} value={h.list_id}>{h.name}</option>
            ))
        }
    </select>
  );
}

Hook feature reactjs

Upvotes: 1

Related Questions