Search code examples
reactjscreate-react-app

How to pass multiple arguments through React Context (from Consumer to Provider)?


I am creating a simple app using create-react-app

And was exploring using React Context API to pass few stuff from one component to another component.

Spice.js

const spiceList = [
  {
    id: 1,
    title: 'Spice 11',
    name: require('./images/spice1.jpeg')
  },
  {
    id: 2,
    title: 'Spice 22',
    name: require('./images/spice2.jpeg')
  }

];

return (
  <div>
    <h1>Welcome to Spices</h1>

 <SpiceContext.Provider value={'Masala'} imgSrc={img3}>
    <SpiceList/>
 </SpiceContext.Provider>
    </div>
  </div>
);

} }

export default Spice;

Consumer in SpiceList Where I plan to retrieve multiple attributes instead of a single value attribute.

How this could be achieved? Thanks

<>
                    <h1>{props.title}</h1>
                    <SpiceContext.Consumer>
                      {spiceContext=> <img src={spiceContext.value} alt={spiceContext.title}/>
                      }
                    </SpiceContext.Consumer>
      </>

SpiceContext

import React from 'react';

const SpiceContext = React.createContext(null);

export default SpiceContext;


Solution

  • First create your object to share.

    const myOptions = [
      {
        key: 1,
        title: 'Title',
        other: 'other',
      },
      {
        key: 2,
        title: 'Title',
        other: 'other',
      }
    ];  
    

    Then pass it down.

    return (
          <div>
            <h1>Welcome to Spices</h1>
    
         <SpiceContext.Provider value={myOptions} imgSrc={img3}>
            <SpiceList/>
         </SpiceContext.Provider>
            </div>
          </div>
        );
    

    Then you will receive those in the same way:

    <h1>{props.title}</h1>
    <SpiceContext.Consumer>
      {(options) => (
        <>
          {options.map((option) => (
            <img key={option.key} src={option.other} alt={option.title}/>
          ))}
        </>
      )}
    </SpiceContext.Consumer>