Yusuf
Yusuf

Reputation: 95

How to access an image link inside an object and show it using react componenets

I have an object (called opp) containing data in this format

  {"randomtext"},
  { "randomtext"}, 
  {flag: "imagelink" , rand1: 23}, 
  {"randometext"} 

i am trying to access the value inside the flag property and and with the help of react components show it

my intended result should be

<img src=" value in flag property"/>

so far i have come up with this

class App extends React.Component {
   
      render() {
       
        return (
          <div> 
          {opp.map(item => <Card  value={item} src={item.flag}/>)}
          </div>
        );
      }
    }
        ReactDom.render(<App />, document.getElementById("container1"));

the below code is held in another file

class Card extends React.Component {   
  render() {
    return (
      <div>
      <h1>{this.props.value}</h1>
           <img src={this.props.src}/>
           </div>
    
    );
  }
}
export default Card;

but whenever i run this it returns a react error saying "objects are not valid as a react child (found: object with keys { flag, rand1}). if you meant to render a collection of children, use an array instead"

ps: would accept edits to this post for readability

Upvotes: 1

Views: 48

Answers (2)

Haider Ali
Haider Ali

Reputation: 1121

Item is the whole object you pass into card component and you are trying to render in the h1 tag of the Card component as value. You should be showing some property value of the object in the h1. e.g this this.props.value[0] will show the first property value in h1.

class Card extends React.Component {   
  render() {
    return (
      <div>
      <h1>{this.props.value[0]}</h1>
           <img src={this.props.src}/>
           </div>
    
    );
  }
}
export default Card;

Upvotes: 1

kooskoos
kooskoos

Reputation: 4859

<h1>{this.props.value}</h1>

value is an object and you are trying to render it in header. Hence the error.

If you really want to print the value object you can stringify it.

Upvotes: 0

Related Questions