mrpbennett
mrpbennett

Reputation: 1956

How to pass return passed data back into a component to display in html

Ok so i have a file which has a bunch of utility functions in a separate file for example:

const imprGuid = () => {
  data.map((result) => {
    return result.request.requestContext.mpcBidRequest.imprGuid;
  });
};

I have my main index.js component like so

const IndexPage = () => {
  return (
    <Layout>
      <main>
        <section id='request' className={sectionStyles}>
          <h2 className={h2Styles}>request</h2>
          <div className='mt-5 flex justify-around'>
            <Btn onClick={() => imprGuid()}>sspBidFloor</Btn>
            <Btn onClick={() => console.log('button was clicked')}>geoData</Btn>

I have a UI of buttons. Which will call the ultil functions separately onClick. Once the function is called i want to display the result within the UI, however I cant seem to wrap my head around two things.

  1. how to display the returned data within the UI. I have already imported it and used it on the onClick but how can i display what is returned else where?
  2. how can change what is display depending on which button is clicked...for example, i click one button to display something i click another button i want to replace previous with new.

Update:

I have added useState but the returned value still isnt showing up.

const IndexPage = () => {
  const [data, setData] = useState();
  ...

button click is

<Btn onClick={() => setData(imprGuid())}>sspBidFloor</Btn>

util function is now:

const imprGuid = () => {
  data.map((result) => {
    let imprGuid = result.request.requestContext.mpcBidRequest.imprGuid;
    console.log(imprGuid);
    return imprGuid;
  });
};

and I am placing data in the component like {data} but nothing is appearing, but the result prints to the console fine. So I am guessing it would return the data ok?


Further Update.

{data.map((result, i) => (
            <>
              {i}: {result}
              <br />
            </>
          ))}

I am now getting Cannot read property 'map' of undefined. However the fix worked and then i refreshed and now it's returning undefined... the state and functions havent changed :(

Upvotes: 3

Views: 651

Answers (1)

Olivier Boiss&#233;
Olivier Boiss&#233;

Reputation: 18113

As Andy said, the imprGuid function doesn't return anything, that's why it's not working.

The function below should solve your problem :

const imprGuid = () => {
  return data.map(result => result.request.requestContext.mpcBidRequest.imprGuid);
};

To add a break line between each element, you can use a <br/> tag.

<code>
  {(data || []).map(el => <>el<br/></>)}
</code>

Upvotes: 2

Related Questions