pass data to component react

// Imagine the directory structure of the app as follows: 
// The parent component actually renders the child components in the app.

App
 └── Parent
   ├── Child
   └── Child2

// Parent Component: Functional Component
const Parent = () => {
    const [data, setData] = useState('');

    const parentToChild = () => {
        setData('This is data from Parent Component to the Child Component.');
    };

    return (
        <div className="App">
            <Child parentToChild={data}/>

            <div>
                <Button primary onClick={() => parentToChild()}>
                    Click Parent
                </Button>
            </div>
        </div>
    );
};

// Child Component: Functional Component
const Child = (parentToChild) => {
    return (
        <div>
            {parentToChild}
        </div>
    )
}

// Parent Component: Class Component
class Parent extends React.Component {
    state = { data: 'Hello World' };
    render() {
        return (
            <div>
                <Child /> //no data to send
                <Child2 dataFromParent={this.state.data} />
            </div>
        );
    }
}

// Child2 Component: Class Component
// Use the variable this.props.dataFromParent 
// to obtain the data passed from parent to child.
class Child2 extends React.Component {
    render() {
        return <div>Data from parent is:{this.props.dataFromParent}</div>;
    }
}


Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source