Home > Enterprise >  create array of JSX elements and pass prop to each element
create array of JSX elements and pass prop to each element

Time:11-13

i am a new in react framework. what i want to do is to create array of JSX elements (Components) for examples:

import Intro from '../Introduction/Intro';
import Skills from '../Skills/Skills';

export const SECTIONS = [<Intro/>, <Skills/>]

const SomeComponent = () => {
const handler = () => {...}
return (
   <div className={classes.container}>
     <div className={classes.fields}>
       {SECTIONS.map((section, i) => {
        return <Fragment key={i}>{section /* for each element i want also pass prop */ }</Fragment>
     })}
     </div>
    <div className={classes.check}>...</div>
  </div>
   ) 
}

so i want to pass handler function to each element in my array

(<Intro foo={handler}/>)

Is it possible to do this?

CodePudding user response:

yes you can do this :

  export const SECTIONS = [Intro, Skills]
  const SomeComponent = () => {
    const handler = () => {...}
    return (
      <div className={classes.container}>
        <div className={classes.fields}>
          {SECTIONS.map((Section, i) => {
            return <Fragment key={i}><Section foo={handler}></Section></Fragment>
          })}
        </div>
        <div className={classes.check}>...</div>
      </div>
    )
  }
  • Related