Skip to content
Advertisement

How to get parent props from child composition component React

My goal is reduce every letter prop from child (Palata) component, how can i achieve this ?

index.js

<Block letter="I" mb={16}>
  <Palata letter="I" start={4} end={9}/>
  <Wall/>
  <Empty/>
  <Palata letter="I" start={10} end={15}/>
  <Empty/>
  <Palata letter="I" start={16} end={17}/>
  <Empty/>
  <Palata letter="I" start={18} end={21}/>
  <Wall/>
  <Palata letter="I" start={22} end={27}/>
  <Empty/>
  <Palata letter="I" start={28} end={33}/>
</Block>

Block.js

export default function Block({ letter, mb, children }) {

    return (
        <div className={"flex mb-" + mb} >
            {children}
        </div>
    )
}

there is a question, how to pass Block component letter prop as data to Palata component or

Palata.js

export default function Palata ({ letter, start, end }) {
  // med postlar
  const mps = ['I4', 'G1', 'E1', 'C1', 'A1', 'I13', 'G10', 'E10', 'C10', 'A10', 'I27', 'G25', 'E25', 'C25', 'A21',]
  const palataNumbers = []

  for (let index = start; index <= end; index++)
    palataNumbers.push(index)

  return (
    <>
      {palataNumbers.map((item, index) => {
        const isMP = mps.includes(letter + item)

        return (
          <button key={index} className={isMP ? 'med-post' : 'palata'}>
            {isMP ? 'MP' : letter + item}
          </button>
        )
      })}
    </>
  )
}

or how to get parent letter prop from inside Palata component?

Thanks for help!

Advertisement

Answer

You can’t access props of parent component.

Also don’t mutate data in body of function, it will run on every render.

  for (let index = start; index <= end; index++)
    palataNumbers.push(index)

Can use context

export const LetterContext = React.createContext('');

export default function Block({ letter, mb, children }) {
  return (
    <LetterContext.Provider value={letter}>
      <div className={'flex mb-' + mb}>{children}</div>
    </LetterContext.Provider>
  );
}

export default function Palata({ start, end }) {
  // med postlar
  const mps = [
    'I4',
    'G1',
    'E1',
    'C1',
    'A1',
    'I13',
    'G10',
    'E10',
    'C10',
    'A10',
    'I27',
    'G25',
    'E25',
    'C25',
    'A21',
  ];
  const palataNumbers = Array(end - start)
    .fill(0)
    .map((_el, index) => index);

  // context
  const letter = React.useContext(LetterContext);

  return (
    <>
      {palataNumbers.map((item, index) => {
        const isMP = mps.includes(letter + item);

        return (
          <button key={index} className={isMP ? 'med-post' : 'palata'}>
            {isMP ? 'MP' : letter + item}
          </button>
        );
      })}
    </>
  );
}

But this way Palata should always be used only inside Block component. Should be a better way to solve your task.

Advertisement