Search code examples
javascriptreactjsreact-functional-component

Why do my props not work in grandchild component?


Tried to transfer data from 2 components to one using the same method, but it is working only for 50%. There are 3 documents: App.js, Hort.js, Hord.js. Transfering from app.js to hort.js is working, but from hord.js to hort.js isn't. What could be the reason?

App.js:

import React from 'react'
import Hort from './Hort'

function App(props) {
    const text1 = 'check1'
    return (
        <Hort test1={text1} />
  );
}

export default App;

Hord.js:

import React from 'react'
import Hort from './Hort'

function Hord(props) {
    const text2 = 'check2'
    return (
        <Hort test2={text2} />
    );
}

export default Hord;

Hort.js:

import React from 'react'
import App from './App'
import Hord from './Hord'

function Hort(props) {
    
    return (
       <div>
            <h1>Just {props.test1}</h1>
            <h2>Just {props.test2}</h2>
        </div>
        )
}

export default Hort;

Solution

  • You are never rendering <Hord>, if a component is never rendered, it won't render what's inside it.

    In your index.js, you probably have code that looks like this:

    import { StrictMode } from "react";
    import ReactDOM from "react-dom";
    
    import App from "./App";
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(
      <StrictMode>
        <App />
      </StrictMode>,
      rootElement
    );
    

    This code indicates that the <App> component will get rendered in the root element from your index.html.

    So starting from the <App> component, you can build your component tree, because you never call <Hord>, it will never render, nor will the components rendered inside <Hord>.

    Render <Hord> inside your <App> component.

    import React from 'react'
    import Hort from './Hort'
    import Hord from './Hord'
    
    function App(props) {
        const text1 = 'check1'
        return (
            <Hort test1={text1} />
            <Hord />
      );
    }
    
    export default App;
    

    As mentioned in the comments, you shouldn't import components that could cause infinite loops.

    import React from 'react'
    // * removed imports
    
    function Hort(props) {
        return (
           <div>
               <h1>Just {props.test1}</h1>
               <h2>Just {props.test2}</h2>
           </div>
        )
    }
    
    export default Hort;