React JSX Question

How to pass more than one argument in component function in React

How to pass more than one argument in components function in React

function Ads(product_title, description) {
return(
<div className = "row" id="user-ads">
<div className = "col-sm-6 col-md-5">
<div className = "thumbnail">
<img src = "img/img1.jpg" alt = "Generic placeholder thumbnail" />
</div>
<div className = "caption">
<div className="border">
<h3>{product_title.title}</h3>
<p>{description.desc}</p>
<button className = "btn btn-primary" role = "button" data-toggle="modal" data-target="#view-detail">View Details
</button>
</div>
</div>
</div>
</div>
);


}

ReactDOM.render(<Ads title="PlayStation 4" desc="Lorem ipsum jipsum Lorem ipsum jipsum"/>, document.getElementById('ads'));


The code above only takes the value of first parameter

Answer Source

Stateless React components only receive a single argument, an object that contains all the props:

function Ads(props) {
  // access props.title
  //        props.desc

  // ...
}

Maybe that becomes more obvious if you look at what the JSX is actually converted to:

// Before:
<Ads title="PlayStation 4" desc="Lorem ipsum jipsum Lorem ipsum jipsum"/>
// After:
React.createElement(
  Ads,
  { title: "PlayStation 4", desc: "Lorem ipsum jipsum Lorem ipsum jipsum" }
);

A common pattern is to use destructuring to get direct access to the props:

function Ads({title, desc}) {
  // ...
}