9

I would like to update the parent state from child component, which renders each object of the array of objects. The main goal of the child component is to update the original value from the array of objects.

I've the following code

Parent:

import { useState } from 'react';
import ExpenseItem from './expenseItem';

function Update({ data }) {
    const [ expenses, setExpenses ] = useState(data);
    return (
        <div>
            {expenses.map((expense, index) => {
                return <ExpenseItem key={index} {...expense} />;
            })}
            <button>Save</button>
        </div>
    );
}

export default Update;

child:

import { useState, useRef } from 'react';

function ExpenseItem({ description, date, credit, debit }) {
    const [ edit, setEdit ] = useState(false);
    const [ expenseDescription, setExpenseDescription ] = useState(description);
    const textInput = useRef();
    const renderDefaultView = () => {
        return <h3 onDoubleClick={() => setEdit(true)}>{expenseDescription}</h3>;
    };
    const renderEditView = () => {
        return (
            <div>
                <input
                    type="text"
                    ref={textInput}
                    defaultValue={expenseDescription}
                    onDoubleClick={() => setEdit(true)}
                />
                <button onClick={() => setEdit(false)}>X</button>
                <button onClick={() => updateValue()}>OK</button>
            </div>
        );
    };
    const updateValue = () => {
        const value = textInput.current.value;
        setExpenseDescription(value);
        textInput.current.defaultValue = value;
        setEdit(false);
    };
    return (
        <div>
            {edit ? renderEditView() : renderDefaultView()}
            <span>{date}</span>
            <p>{debit}</p>
            <p>{credit}</p>
        </div>
    );
}

export default ExpenseItem;
1
  • Is it the expenses property in the Update Component that you want to access and change from the ExpenseItem Components? Commented Dec 14, 2019 at 3:10

1 Answer 1

6

Once way, is to pass the parent state property (expenses) and the function that updates it (setExpenses) to the child Component via the props:

Parent:

import { useState } from 'react';
import ExpenseItem from './ExpenseItem';

function Update({ data }) {
    const [ expenses, setExpenses ] = useState(data);
    return (
        <div>
            Checking: { expenses[0].description } | { expenses[1].description }
            <hr/>
            {expenses.map((expense, index) => {
                return <ExpenseItem key={index} index={index} expenses={expenses} setExpenses={setExpenses} />;
            })}
            <button>Save</button>
        </div>
        );
}

export default Update;

Child:

import { useState, useRef } from 'react';

function ExpenseItem( props ) {
    let { description, date, credit, debit } = props.expenses[props.index];
    const setExpenses = props.setExpenses;
    const [ edit, setEdit ] = useState(false);
    const [ expenseDescription, setExpenseDescription ] = useState(description);
    const textInput = useRef();
    const renderDefaultView = () => {
        return <h3 onDoubleClick={() => setEdit(true)}>{expenseDescription}</h3>;
    };
    const renderEditView = () => {
        return (
            <div>
                <input
                    type="text"
                    ref={textInput}
                    defaultValue={expenseDescription}
                    onDoubleClick={() => setEdit(true)}
                />
                <button onClick={() => setEdit(false)}>X</button>
                <button onClick={() => updateValue()}>OK</button>
            </div>
        );
    };
    const updateValue = () => {
        const value = textInput.current.value;
        setExpenseDescription(value);
        textInput.current.defaultValue = value;
        setEdit(false);
        const expenses = [ ...props.expenses ]; // Get a copy of the expenses array
        // Replace the current expense item
        expenses.splice( props.index, 1, {
            description: value, date, credit, debit
        }); 
       // Update the parent state
        setExpenses( expenses );
        
    };
    return (
        <div>
            {edit ? renderEditView() : renderDefaultView()}
            <span>{date}</span>
            <p>{debit}</p>
            <p>{credit}</p>
        </div>
    );
}

export default ExpenseItem;
  • This can get really complicated as you move along, so the best option is to look for some sort of State Management solution, like using the Context API.

  • Also, take a look at this interesting post that talks about using the map index value as a key value: Index as a key is an anti-pattern


Full source code:

import React from 'react';
import ReactDOM from 'react-dom';
import { useState, useRef } from 'react';

function ExpenseItem( props ) {
    let { description, date, credit, debit } = props.expenses[props.index];
    const setExpenses = props.setExpenses;
    const [ edit, setEdit ] = useState(false);
    const [ expenseDescription, setExpenseDescription ] = useState(description);
    const textInput = useRef();
    const renderDefaultView = () => {
        return <h3 onDoubleClick={() => setEdit(true)}>{expenseDescription}</h3>;
    };
    const renderEditView = () => {
        return (
            <div>
                <input
                    type="text"
                    ref={textInput}
                    defaultValue={expenseDescription}
                    onDoubleClick={() => setEdit(true)}
                />
                <button onClick={() => setEdit(false)}>X</button>
                <button onClick={() => updateValue()}>OK</button>
            </div>
        );
    };
    const updateValue = () => {
        const value = textInput.current.value;
        setExpenseDescription(value);
        textInput.current.defaultValue = value;
        setEdit(false);
        const expenses = [ ...props.expenses ]; // Get a copy of the expenses array
        // Replace the current expense item
        expenses.splice( props.index, 1, {
            description: value, date, credit, debit
        }); 
       // Update the parent state
        setExpenses( expenses );
        
    };
    return (
        <div>
            {edit ? renderEditView() : renderDefaultView()}
            <span>{date}</span>
            <p>{debit}</p>
            <p>{credit}</p>
        </div>
    );
}

function Update({ data }) {
    const [ expenses, setExpenses ] = useState(data);
    return (
        <div>
            { expenses[0].description } | { expenses[1].description }
            <hr/>
            {expenses.map((expense, index) => {
                return <ExpenseItem key={index} index={index} expenses={expenses} setExpenses={setExpenses} />;
            })}
            <button>Save</button>
        </div>
        );
}

// export default Update;
ReactDOM.render( 
  <Update data={[
    {
    description:"Title 1",
    date: "2018",
    credit: "100",
    debit: "debit"
    },
    {
      description:"Title 2",
      date: "2019",
      credit: "199",
      debit: "card"
      }
    ]} />, 
  document.querySelector("#root") 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

6
  • Thanks for your time! First of all I'm build that app with nextjs. Answering your first question, the expenses data is coming from another parent component, which is the page itself, that renders a form to send to a server an xls folder, and returns a json.
    – asotos
    Commented Dec 15, 2019 at 0:38
  • My idea is to edit the json file in the expenseItem component, then creat a button on the parent component, to fetch it to the database
    – asotos
    Commented Dec 15, 2019 at 0:56
  • thanks a lot, it worked as I wanted. If I'm using this components only to updated the data before saving it to the database, do you think it's worth to implement a state management solution to it?
    – asotos
    Commented Dec 15, 2019 at 10:13
  • 1) If your application stays as it is (often this is not the case, as you'll nee to add more features or modify the code in some way) then maybe you can use this -not very elegant- solution. If you decide to change more data from the array, it will quickly become too complicated to work with. Commented Dec 15, 2019 at 11:50
  • 1
    2) I think, this is a good case where you should look for a state management solution like Context API or Redux, implement it alongside the current solution and compare the results. After a while you will understand what these tools have to offer you and decide which solution best fits your needs. In any case, you will have familiarised yourself with what is probably the most important concept in React. Commented Dec 15, 2019 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.