Add method to React component

Last Updated: August 1, 2021

Now we will see how to add a method to React component. If you are not familiar with creating React components you can refer to this tutorial
I have the following code inside the index.js file.

import React from 'react'
import {render} from 'react-dom'
import {Product} from './product.js'

render(

    ,
    document.getElementById('root')

)

Then I will create a method in my component file product.js

export const Product = createReactClass({

	
    calculateDiscount(discount){
       return discount/100*this.props.unit_price*this.props.qty
    },


	render(){
		return (
<div>
<ul>
<li>Product Name :{this.props.name}</li>
<li>Unit Price : {this.props.unit_price}</li>
<li>Qty :{this.props.qty}</li>
</ul>
<div>Total Discount {this.calculateDiscount(this.props.discount)}</div>
</div>
)
	}
})




  • Product Name :{this.props.name}
  • Unit Price : {this.props.unit_price}
  • Qty :{this.props.qty}
Total Discount {this.calculateDiscount(this.props.discount)}
			)
	}
})

You can see the calculateDiscount() method in code and you can call the method this.calculateDiscount()