Sireini
Sireini

Reputation: 4262

How to set dynamically prop to a component in reactjs

I have a listitem component which looks like this:

import React, { Component } from 'react';
import './App.css';
// import $ from 'jquery';

class ListItem extends Component {
  render() {
      let message = "";
    return (
         <div className="item  col-xs-4 col-lg-4">
            <div className="thumbnail">
                <img className="group list-group-image" src="http://placehold.it/400x250/000/fff" alt="" />
                <div className="caption">
                    <h4 className="group inner list-group-item-heading">Product title {title}</h4>
                    <p className="group inner list-group-item-text">
                      {message}
                    </p>
                </div>
            </div>
        </div>     
    );
  }
}

export default ListItem;

As you see I want to dynamically set the title and the message of the listItem. How do I use an prop like below to set the title and the message?

And here I reuse this component in PageContent.jsx:

<ListItem message="tester"></ListItem>

How do I give the title and message to its component to set it dynamically?

Upvotes: 0

Views: 731

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104369

First pass the values message and title in the props:

<ListItem message="hello" title='world'></ListItem>

Then use this.props.message and this.props.title inside ListItem component to access these values.

Like this:

class ListItem extends Component {
  render() {

    console.log(this.props.message, this.props.title);

    return (
         <div className="item  col-xs-4 col-lg-4">
            <div className="thumbnail">
                ....
                      Product title {this.props.title}</h4>
                ....
                      {this.props.message}
                ....
            </div>
        </div>     
    );
  }
}

I will suggest you to read the react doc because this is a very basic part.

Note: I think you are using the jquery with react, that is not a good idea we should avoid that.

Upvotes: 1

Related Questions