Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use conditional rendering in React but a variable storing the element is not defined?

I have a small forum that conditionally renders some buttons, but I could not get it to work since a variable is always ‘undefined’

function NewExpense(props) {
  const [isEditing, setIsEditing] = useState(false);

  const startEditingHandler = () => {
    setIsEditing(true);
  };
  
  const saveExpenseDataHandler = (enteredExpenseData) => {
    const expenseData = {
      ...enteredExpenseData,
      id: Math.random().toString(),
    };
    
    props.onAddExpense(expenseData);

//showedElement is not defined in the return statement??
    let showedElement = isEditing ? (
      <ExpenseForm onSaveExpenseData={saveExpenseDataHandler}></ExpenseForm>
    ) : (
      <button onClick={startEditingHandler}>Add New Expense</button>
    );
  };

  return (
    <div className="new-expense">
   //showedElement is not defined
      {showedElement}
    </div>
  );
}

What did I do wrong? I made a variable and conditionally set its value to the rendered element, but React kept yelling at me that it was not defined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Why do you define a local scope variable showedElement in saveExpenseDataHandler?

Because its scope is local (local inside function), it’s always undefined.

It’s enough to add it in return function.

Check the following code.


function NewExpense(props) {
  const [isEditing, setIsEditing] = useState(false);

  const startEditingHandler = () => {
    setIsEditing(true);
  };

  const saveExpenseDataHandler = (enteredExpenseData) => {
    const expenseData = {
      ...enteredExpenseData,
      id: Math.random().toString(),
    };

    props.onAddExpense(expenseData);
  };

  return (
    <div className="new-expense">
      {isEditing ? (
        <ExpenseForm onSaveExpenseData={saveExpenseDataHandler}></ExpenseForm>
      ) : (
        <button onClick={startEditingHandler}>Add New Expense</button>
      )}
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading