Why onClick event doesn't change the props.title in React

Viewed 227

I wanna change the

title

by clicking the button but it doesn't change, can I have an explanation why is that happens?

import './ExpenseItem.css';
import ExpenseDate from './ExpenseDate';
import Card from './Card';

function ExpenseItem(props){
    let title  = props.expenseTitle;

    function clickedFunc(){
        title = "Update!";
    }
    return(
        <Card className='expense-item'>
            <ExpenseDate expenseDate={props.expenseDate}></ExpenseDate>
            <div className='expense-item__description'>
                <h2>{title}</h2>
                <div className='expense-item__price'>
                    &#8377;{props.expenseAmount}
                </div>
            </div>
            <button onClick={clickedFunc}>Click</button>
        </Card>
    );    
}

export default ExpenseItem;
1 Answers

This is not how data is handled with React.

The title should be stored in a state variable (see useState).

Once the data is stored in a state variable, you will have to set it with setState. When setState is called in React, the component holding the state variable re-renders. This will in turn cause your ExpenseItem component to re-render because it is a child component of whatever higher level component passed it props.

In your parent component, you should see something like:

require { useState } from 'react';

const ParentComponent = (props) => {
   
   const [title, setTitle] = useState('Original Title');

   ...
   ...
   ...

   return (
      <div className="ParentComponent">
         <ExpenseItem
            title={title}
            setTitle={setTitle}
            expenseAmount={expenseAmount}
         />
      </div>
   )
}

Then, in your clickedFunc() function:

function clickedFunc() {
   props.setTitle("Update!");
}
Related