Home > Net >  Pass props and use ID again
Pass props and use ID again

Time:04-23

I have a component that passes props to another component. Inside the component the props have been passed to, I declare the parameter set new variable and get the last item of the array like this:

var lastItem = passedProp[passedProp - 1] || null

My question is how do I pass this property back to another component to use in a global service I am using to run inside a function. From what I am aware props can only be passed down in React, not up? Please correct me if I am wrong. The end result I want to achieve is to use this property's ID in function I am using in global service.

CodePudding user response:

read about lifting state up ... https://reactjs.org/tutorial/tutorial.html#lifting-state-up

CodePudding user response:

You can pass a function to the child and the child can pass the information through this function.

I let you an example that you can copy & paste to see how it works :)

import React  from 'react';

function ChildComponent(props) {
  const { data, passElementFromChild } = props;
  const lastElement = data[data.length - 1] || null;

  setTimeout(() => {
    passElementFromChild('this string is what the parent is gonna get');
  }, 300);

  return (
    <div>Last element of the array is: {lastElement}</div>
  );
}

function Question17() {

  const data = ['firstElement', 'middleElement', 'lastElement']

  const passElementFromChild = (infoFromChild) => {
    console.log("infoFromChild: ", infoFromChild);
  }

  return (
    <ChildComponent data={data} passElementFromChild={passElementFromChild} />
  );
}

export default Question17;
  • Related