1

I want to display all images in Array, I using map but it didn't work

export default class Content extends Component {
    constructor(){
        super();
        this.state = {
            gifs: []
        }
    }

    componentDidMount(){
        axios.get('https://api.giphy.com/v1/gifs/trending?api_key=nNwaquW24K8gLDmrxGTmawppQoTkXxLQ&tag=&rating=G')
        .then( response => {
            this.setState({ gifs: [...this.state.gifs, response.data.data] }); // This line is different
        })
        .catch(function(error){
            console.log(error);  
        })

    }

    render() {
        if (this.state.gifs){
        return (
                <div className="container">
                    {this.state.gifs.map( gif =>(
                    <div className="card mt-5" style={{width: 224 + 'px'}} key={gif[0].id}>
                    <img className="card-img-top" src={gif[0].images.preview_gif.url}alt="test"></img>
                    <div className="card-body">
                        <h4 className="card-title">{gif[0].title}</h4>
                    </div>
                    </div>
                        ))}
              </div>
        );
    }
    }
}

I expect all images showing up results of the code

And this is my Data

My data from API

This is data from my State

4 Answers 4

2

What you did was inserting the array of gifs from the api inside the state array, like this { gifs: [[gifsarr]]} response.data.data is already an array of objects so just assign them to this.state.gifs

An empty array will always return true if you check for if (this.state.gifs) {} you will have to check if the length is > 0

class Content extends React.Component {
  constructor() {
    super();
    this.state = {
      gifs: []
    };
  }

  componentDidMount() {
    axios
      .get(
        "https://api.giphy.com/v1/gifs/trending?api_key=nNwaquW24K8gLDmrxGTmawppQoTkXxLQ&tag=&rating=G"
      )
      .then(response => {
        this.setState({ gifs: response.data.data }); // This line is different
      })
      .catch(function(error) {
        console.log(error);
      });
  }

  render() {
    if (!this.state.gifs.length) return null;

    return (
      <div className="container">
        {/* gif is an object and not an array you dont need to access it by index */}
        {this.state.gifs.map(gif => (
          <div className="card mt-5" style={{ width: 224 + "px" }} key={gif.id}>
            <img
              className="card-img-top"
              src={gif.images.preview_gif.url}
              alt="test"
            />
            <div className="card-body">
              <h4 className="card-title">{gif.title}</h4>
            </div>
          </div>
        ))}
      </div>
    );
  }
}

sandbox

Sign up to request clarification or add additional context in comments.

3 Comments

Please check at data from API, if I don't put [0] it would be returning an error
@SyahrizalSetiawan i also updated the way you access gif properties inside the map function, just copy the component from my answer
@SyahrizalSetiawan I've added a sandbox take a look
0

As per your code, it will be showing of 1st image in the array. as you have provided [0]. Please use below code and check it out.

<div className="container">
  {this.state.gifs.map( gif =>(
    <div className="card mt-5" style={{width: 224 + 'px'}} key={gif.id}>
      <img className="card-img-top" src={gif.url} alt="test"></img>
      <div className="card-body">
          <h4 className="card-title">{gif.title}</h4>
      </div>
    </div>
  ))}
</div>

3 Comments

it not work, TypeError: Cannot read property 'preview_gif' of undefined. please look at data there is 0 which If I don't give[0] it would be return error
I have edited do check again. Just replace the parameter as per api
Can you provide the working code. Or error. Or output you are getting. Can add console.log(this.state.gifs) in render
0

Try:

render() {
    return (
      <div className="container">
        {this.state.gifs.map(gif => (
          <div className="card mt-5" style={{ width: 224 + "px" }} key={gif.id}>
            <img
              className="card-img-top"
              src={gif.images.preview_gif.url}
              alt="test"
            />
            <div className="card-body">
              <h4 className="card-title">{gif.title}</h4>
            </div>
          </div>
        ))}
      </div>
    );
  }

You need not worry about the else part, as when the list will be blank, none of the inner div's will get rendered. i.e. there will be an empty .container div

Comments

0

How you're generating the array is a specific part of your code. You can make a Code Sandbox for us to test it.

But as far as displaying images from an array of src's, that's what I usually do:

NOTE: When you map an array, React will demand a key property on each element of the resulting array. You can use the index number, as long as you're not planning on re-ordering the items. If you do, you need some sort of unique ID to use as a key.

function App() {
  
  const imagesArray = [
    "https://upload.wikimedia.org/wikipedia/commons/e/ee/Thumbup.jpg",
    "https://sociorocketnewsen.files.wordpress.com/2013/11/thumb-top1.jpg?w=640",
    "https://news.power102fm.com/wp-content/uploads/2014/02/thumbs-up-.jpg"
  ];
  
  const imageItems = imagesArray.map((image,index) => 
    <div key={index} className="imageContainer">
      <img src={image} className="image"/>
    </div>
  );
  
  return(
     <React.Fragment>
      {imageItems}
     </React.Fragment>
  );
}

ReactDOM.render(<App/>,document.getElementById('root'));
.imageContainer {
  height: 100px;
  width: 100px;
  border: 1px solid silver;
  margin-top: 5px;
}

.image {
  height: 100%;
  width: 100%;
  object-fit: cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.