Answers for "pass data react"

2

pass data react

//place where you will send
import { useHistory } from "react-router-dom";

const history = useHistory();
history.push({
	pathname: "/home",
	state: {name : 'demo'},
});

//place where you will get data
import { useLocation } from 'react-router';

const location = useLocation();
console.log(location.state);
Posted by: Guest on October-02-2021
0

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>;
    }
}
Posted by: Guest on July-22-2021

Code answers related to "pass data react"

Code answers related to "Javascript"

Browse Popular Code Answers by Language