Home > front end >  How to get data from child via callBack and to add new argument to it in reactjs?
How to get data from child via callBack and to add new argument to it in reactjs?

Time:03-23

I am having a parent component from where i pass callBack to a child component to update value on change(dataToAdd is the data coming from the child component). But i need to be able to add one more argument that is only for the parent. if I add collectionName to handleAdd I don't get the data from the child anymore. how can i keep the data from the child component and have collectionName argument as well?

Here is the parent code:

const ParentComponent = ()=> {

const handleAdd = (dataToAdd, collectionName) => { 
 if (collectionName === 'second-jobs') {
        localSecondJobsOptions.push({
          _id: Math.random().toString(),
          name: dataToAdd.value,
          userAdded: true,
          selected: true,
        });
    } else if (collectionName === 'courses') {
      localCoursesOptions.push({
        _id: Math.random().toString(),
        name: dataToAdd.value,
        userAdded: true,
        selected: true,
      });
    }
}

   <CheckboxModal
   onAdd={() => handleAdd('second-job')}/>
}
Here is the child component:
const ChildComponent = ({onAdd}) => {
 
 const [addValue, setAddValue] = useState('');

 const localOnAdd = () => {
    onAdd({ value: addValue });
    setAddValue('');
  }
<Container>
      <Row className="ml-1 mr-4">
        <Col md="8">
          <Input
            onChange={changeAddValue}
            value={addValue}
            placeholder={addFieldPlaceholder}
          />
        </Col>
        <Col sm="12" md="4">
          <Button
            label="Add"
            variant="Button"
            onClick={localOnAdd}
          />
        </Col>
      </Row>
      <Row className="ml-1 mr-4">
        <Col md="8"></Col>
        <Col sm="6" md="4">
          <div className="btn-wrapper">
            <Button
              label="Opslaan"
              variant="Button-outline"
              onClick={localOnSave}
            />
          </div>
        </Col>
      </Row>
    </Container>
}

CodePudding user response:

in parent component use a function that returns a function:

const ParentComponent = ()=> {

const handleAdd = (collectionName) => (dataToAdd) => { 
 if (collectionName === 'second-jobs') {
        localSecondJobsOptions.push({
          _id: Math.random().toString(),
          name: dataToAdd.value,
          userAdded: true,
          selected: true,
        });
    } else if (collectionName === 'courses') {
      localCoursesOptions.push({
        _id: Math.random().toString(),
        name: dataToAdd.value,
        userAdded: true,
        selected: true,
      });
    }
}

   <CheckboxModal
   onAdd={handleAdd('second-jobs')}/>
}

so now handleAdd('second-jobs') is a function that accept dataToAdd as parameter and in this case the collectionName is second-jobs

  • Related