Home > OS >  NextJs, React, passing data through two components
NextJs, React, passing data through two components

Time:05-04

I have a variable in my child component that holds the data of its height. I need to pass it through its parent and into the parent's parent. I am able to pass it to the parent, but don't understand why passing it to the parent's parent isn't working. The error I am getting is:

Unhandled Runtime Error
TypeError: props.func is not a function

Source
components\layout.js (22:10) @ Object.pull_data [as func]

  20 |  const navHeight = data;
  21 |   console.log(navHeight); 
> 22 |   props.func(navHeight);

  24 | }

Child component:

export default function Navbarmain(props) {

  const ref = useRef();
  useEffect(() => {
    const navHeight = ref.current?.clientHeight;
    props.func(navHeight);
  }, []);


  return (
    <div ref={ref}>

Child's parent:

export default function Layout({ children, home }, props) {

  const pull_data = (data) => {

   const navHeight = data;
    console.log(navHeight); // Correctly outputs Height of child component
    props.func(navHeight);  // Attempt to do a repeat of what I just did

  }

  return (
    <div className={styles.layoutWrap}>
      <Navbarmain func={pull_data}></Navbarmain>

Parent's parent:

export default function Home({ allPostsData }) {
      const pull_data = (data) => {
    
        const navHeight = data;
         console.log(navHeight); 
    
       }
     
    
    
      return (
        <div>
          <Layout home func={pull_data}>

CodePudding user response:

Problem is in the Child's parent' s component props. You are mixing props inside curly braces with props ({ children, home }, props). If you refactor in this way it will work without problem

https://codesandbox.io/embed/fervent-cohen-td6sig?fontsize=14&hidenavigation=1&theme=dark

export default function Layout({ children, home, func }) {

  const pull_data = (data) => {

   const navHeight = data;
    console.log(navHeight); // Correctly outputs Height of child component
    func(navHeight);  // Attempt to do a repeat of what I just did

  }

  return (
    <div className={styles.layoutWrap}>
      <Navbarmain func={pull_data}></Navbarmain>
  • Related