Passing Data from Parent to Child In React - reactjs

I am testing if I can pass data from the parent App.js to a child component named Contact. I want to pass data when clicking on a button.
Here is the App.js file:
import React, { useState } from 'react';
import { Button } from 'semantic-ui-react';
import './App.css';
import Header from './Components/Header';
import Tabs from './Components/Tabs';
import Footer from './Components/Footer';
import SimpleMap from './Components/SimpleMap';
import NewPatient from './Components/NewPatient';
import Contact from './Components/Contact';
function App() {
const [data,setData] = useState(false);
const parentToChild = () => {
setData("This is information from parent to child.");
}
return (
<div className="App">
<Header />
<Contact parentToChild={data} />
<Tabs>
<div label="Home" class="home-page">
<img src="https://news.usc.edu/files/2020/06/covid_vaccine_stock.jpg"></img>
</div>
<div label="New Patient">
<NewPatient />
</div>
<div label="Locations">
<SimpleMap />
</div>
<div label="Appointments">
</div>
</Tabs>
<Footer />
</div>
);
}
export default App;
Here is the child component I want the data to be displayed from the parent data when I click on the button:
import React from 'react';
import './footer.css'
function Footer({parentToChild})
{
return (
<div className="Footer">
<div className="container">
<div className="row">
<div className="col">
<h4 className="block ">About Us</h4>
</div>
<div className="col">
<h4 onClick={() => parentToChild(true)} className="block" >Contact</h4>
</div>
<div className="col">
<h4><a className="block" href={"https://www.cdc.gov/coronavirus/2019-ncov/faq.html"}>COVID-19 FAQ</a></h4>
</div>
<div className="col">
<h4 className="block"><a className="block" href={"https://www.cdc.gov/coronavirus/2019-ncov/if-you-are-sick/quarantine.html"}>CDC Guidelines</a></h4>
</div>
</div>
</div>
</div>
);
}
export default Footer;
I am testing this functionality because I want to eventually display a popup form when I click on a button. I want to use the data from the parent to trigger a popup in a child component. The following code says that parentToChild is not a function. Why do I get this error?

You need to pass your parentToChild function to your Footer Component:
<Footer parentToChild={parentToChild}/>
And if you want to show data from your child, you will need to declare it in your params:
const parentToChild = (input) => {
console.log('Info from child' ,input);
setData("This is information from parent to child.");
}

You must pass that information via props to the Footer component,
<Footer parentToChild={parentToChild} />
This will trigger the callback.

you can use state.
const [state, setState] = useState('')
App.js
const buttonThatYouWantTobeClicked = (dataShouldGotoComponent) => {
setState(dataShouldGotoComponent)
}
<Footer data={state}/>
then in footer.js you can check if value of props is not undefiend or null, so do something

Related

React JS Navigation Bar

App.js
import NewsSec from "./News/NewsSec";
import ScoreSec from "./ScoreSec/ScoreSec";
import Menu from "./Sidebar/Menu";
import "./styles.css";
import { GiHamburgerMenu } from "react-icons/gi";
import React, { useState } from "react";
export default function App() {
const [showMediaIcons, setShowMediaIcons] = useState(false);
return (
<div className="App">
<div className="head">
<div className="navicon">
<a
href="/"
onClick={() => {
setShowMediaIcons(!showMediaIcons);
}}
>
<GiHamburgerMenu />{" "}
</a>
</div>
<div className="logo">Project</div>
<div className="weather">weather section</div>
</div>
<div className="main">
<div className="nav-section">
<Menu classes={showMediaIcons ? "mobile-view navbar" : "navbar"} />
</div>
<div className="news-section">
<NewsSec />
</div>
<div className="score-section">
<ScoreSec />
</div>
</div>
</div>
);
Menu.js
import React from "react";
import "./Navbar.css";
const Menu = (props) => {
return (
<>
<div className={props.classes}>
<ul>
<li>Home</li>
<li>News</li>
<li>Sports</li>
<li>Weather</li>
<li>About</li>
</ul>
</div>
</>
);
};
export default Menu;
i was trying to make a responsive navigation bar. the navigation bar is actually a sidebar. i used the props to pass the 'className' from App.js to Menu.js because i called the function in App.js
For testing, I tried changing the nav colour to Red. But on clicking Hamburger icon, the colour changes to Red and changed back to normal automatically. Please help folks
It seems that a might be reloading the page with href="/", resetting the state showMediaIcons to its initial value of false.
If the purpose of GiHamburgerMenu is to toggle display for Menu, it might not need to be wrapped in a, instead try add the onClick on the icon or on the wrapping div:
<div className="navicon">
<GiHamburgerMenu
onClick={() => {
setShowMediaIcons((prev) => !prev);
}}
/>
</div>

How to change attribute of a child component from parent in React?

I'm having a Child Component with img & h5 elements.I want to change the image and heading content in each component without rewriting the whole code of it.
Parent Component
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Child from "./services";
const Navbar = () => {
return (
<div className="d-flex flex-row justify-content-center">
<Child/>
<Child/>
<Child/>
<Child/>
</div>
);
};
export default Navbar;
Child component:
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
const Child = (props) => {
return (
<>
<div className="ser-wrapper">
<img src="https://api.time.com/wp-content/uploads/2019/08/better-smartphone-photos.jpg" id="myImage"/>
<h5>Heading 1</h5>
</div>
</>
)
};
export default Child;
I tried sending images SRC as props but didn't work the way I wanted. I want to get different images and different heading content for each component.
Parent component
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Child from "./services";
const Navbar = () => {
return (
<div className="d-flex flex-row justify-content-center">
<Child heading="Heading 1" imgSrc="https://api.time.com/wp-content/uploads/2019/08/better-smartphone-photos.jpg" />
<Child heading="Heading 2" imgSrc="https://media.istockphoto.com/photos/coahuilan-box-turtle-picture-id93385233?k=20&m=93385233&s=612x612&w=0&h=7pdWzLGa-XzIdvPvUsXzF91RomisLiGPiDnlr3iP00A=" />
// ...etc
</div>
);
};
export default Navbar;
Child component
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
const Child = (props) => {
return (
<>
<div className="ser-wrapper">
<img src={props.imgSrc} id="myImage"/>
<h5>{props.heading}</h5>
</div>
</>
)
};
export default Child;
you will need to pass props to the child component from parent component
Parent Component
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Child from "./services";
const Navbar = () => {
return (
<div className="d-flex flex-row justify-content-center">
<Child title="Heading 1" imgSrc="img-url"/>
<Child title="Heading 2" imgSrc="img-url"/>
<Child title="Heading 3" imgSrc="img-url"/>
</div>
);
};
export default Navbar;
Child component:
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
const Child = (props) => {
return (
<>
<div className="ser-wrapper">
<img src={props.imgSrc} id="myImage"/>
<h5>{props.title}</h5>
</div>
</>
)
};
export default Child;
There are multiple ways to solve this problem.
You can send array of imgSrc and heading to child component and child component will loop over all these and render all of them like:-
Parent Component
data = [
{
imgSrc:
'https://api.time.com/wp-content/uploads/2019/08/better-smartphone-photos.jpg',
heading: 'heading1',
},
{
imgSrc:
'https://api.time.com/wp-content/uploads/2019/08/better-smartphone-photos.jpg',
heading: 'heading2',
},
];
render() {
return (
<div>
<Child data={this.data} />
<p>Start editing to see some magic happen :)</p>
</div>
);
}
}
Child Component
<div>
{data.map((obj) => {
return (
<div className="ser-wrapper">
<img src={obj.imgSrc} id="myImage" />
<h5>{obj.heading}</h5>
</div>
);
})}
</div>
Working Example:- https://stackblitz.com/edit/react-ts-l8ubqc?file=index.tsx
Other way is to use <Child> component multiple times in parent component and pass data as props
Parent Component
<div>
<Child heading='headingName' imgsrc = 'srcurl'/>
<Child heading='headingName' imgsrc = 'srcurl'/>
.
.
</div>
Child Component
const {imgsrc,heading} = props
return (
<>
<div>
<img src={imgsrc} />
<h5>{heading}</h5>
</div>
</>
)

i want to build sidebar on my own but the function don't work

Sorry for my bad English speak please help me to build a responsive sidebar menu. when i try to build a sidebar menu responsive I reach this type of error : TypeError: document.getElementByClassName is not a function. I haven't an idea where's the error exactly so this is my code of the sidebar menu:
import React from 'react';
import {useEffect} from 'react';
import SideNav, { Toggle, Nav, NavItem, NavIcon, NavText } from '#trendmicro/react-sidenav';
import '#trendmicro/react-sidenav/dist/react-sidenav.css';
import {listProducts} from '../actions/productActions';
import {useSelector, useDispatch} from 'react-redux';
function w3_open() {
document.getElementByClassName("sidebar").style.width = "100%";
document.getElementByClassName("sidebar").style.display = "block";
}
function w3_close() {
document.getElementByClassName("sidebar").style.display = "none";
}
export default function SideBarMenu() {
const dispatch = useDispatch();
useEffect(()=> {
dispatch(listProducts);
}, [])
const productList = useSelector((state) => state.productList);
const {products} = productList;
console.log(products);
return (
<div className="wrapper" >
<div className="section">
<div className="top_navbar">
<div className="hamburger">
<a href="#">
<i className="fa fa-bars" onClick={w3_open(), w3_close()} ><span className="bar-icon"> All products </span></i>
</a>
</div>
</div>
</div>
<div className="sidebar">
profile image & text
menu item
</div>
</div>
)
}
and this is the app.js file :
import React from 'react';
import {BrowserRouter, Routes, Route} from 'react-router-dom';
import HomePage from './Pages/HomePage';
import ProductPage from './Pages/productPage';
import SideBarMenu from './components/SideBarMenu';
function App() {
return (
<BrowserRouter>
<div className="grid-container" >
<header className="row" >
<div>
<a className="brand" href="/">My shop</a>
</div>
<div>
Cart
Sign In
</div>
</header>
<main>
<SideBarMenu ></SideBarMenu>
<Routes>
<Route path='/product/:id' element={<ProductPage /> } />
<Route path='/' element={<HomePage />} exact />
</Routes>
</main>
<footer className="row center" >All right reserved</footer>
</div>
</BrowserRouter>
);
}
export default App;
document.getElementByClassName(...) doesn't exist in JavaScript. You should use document.getElementsByClassName(...) (notice the plural in Elements).
Replace document.getElementByClassName("sidebar") with document.getElementsByClassName("sidebar")[0].
Update
To fix the error that you have right now, I would suggest to use a variable and useState Hook to display or hide the sidebar.
Example:
const [open, setOpen] = useState(false)
const handleSidebar = () => {
setOpen(!open)
}
return(
<div className = "wrapper" >
<div className = "section">
<div className = "top_navbar">
<div className = "hamburger">
<a href = "#">
<i className="fa fa-bars" onClick = {handleSidebar}><span className = "bar-icon"> All products </span></i>
</a>
</div>
</div>
</div>
{ open
? <div className = "sidebar">
profile image & text menu item
</div>
: null
}
</div>
)

How to pass a certain LIST from one component to another component in REACT JS?

How to pass a certain LIST from one component to another component in REACT? This is the code, I could not pass the LIST to another components. I tried many ways but still couldn't pass the list.
Please me to solve the problem. So, I want to use the fetched LIST in another component.
Child Component (in a same js of parent component)
import React, { useState, useEffect } from "react";
import FavoriteBorderIcon from '#material-ui/icons/FavoriteBorder';
import AddBoxIcon from '#material-ui/icons/AddBox';
import ExposureIcon from '#material-ui/icons/Exposure';
import HighlightsData from "./HighlightsData";
export function HighlightsGrid(props){
const [name, setTitle] = useState(props.title);
const [image, setImage] = useState(props.imgsrc);
const [amount, setAmount] = useState(props.price);
const LIST=[name, image, amount];
const onSubmit=()=>{
const LIST={image, name, amount}
console.log(datas)
}
return(
<div className="carddd">
<li className="card-item double">
<a href="#">
<h1 className="heightLight">Highlight</h1>
<div className="highlights">
<figure className="card">
<img src={props.imgsrc} alt="img." value={image} onChange={e=>setImage(e.target.value )}/>
<button onClick={onSubmit} className="likeBtn">
<FavoriteBorderIcon />
400
</button>
<figcaption className="caption">
<h3 className="caption-title" value={name} onChange={e=>setTitle(e.target.value)}>{props.title}</h3>
<p>
{props.desc}
</p>
</figcaption>
</figure>
</div>
</a>
<nav id="single-na" className="single-na menu" role="navigation">
<ul>
<li>
<a value={amount} onChange={e=>setAmount(e.target.value )} className="default">
Nrs: <b>{props.price}</b>
</a>
</li>
<li className="defs">
<button>
<ExposureIcon />
</button>
add to shop
</li>
<li className="defs">
<button >
<AddBoxIcon />
</button>
Add To Cart
</li>
</ul>
</nav>
</li>
</div>
)
}
Parent component
function Highlights(){
return(
<>
{HighlightsData.map((val,index)=>
{
return(
<HighlightsGrid
key={val.id}
imgsrc={val.imgsrc}
title={val.title}
desc={val.desc}
price={val.price}
/>
);
})}
</>
);
}
export {Highlights } ;
The list can be passed from parent to child by simply passing list as props .
Parent.js
import React from "react";
import Child from "./Child";
import "./App.css";
function App() {
const List = [1, 3, 2, 4, 5];
return (
<div className="App">
<Child list={List} />
</div>
);
}
export default App;
and Child.js as
import React from "react";
import { Card } from "#material-ui/core";
function Child({ list }) {
return (
<div>
{list.map((value, index) => {
return (
<>
<br />
<Card
style={{ marginTop: "3px", margin: "0px auto", width: "200px" }}
>
Double of {value} is {value * 2}
</Card>
</>
);
})}
</div>
);
}
export default Child;
This will give the result
Considering you want to pass the list to another component that is neither child nor parent of the list's origin component, I would suggest the use of a context.
In short, you'll want to create a context provider at a higher level so that it is parent to both your list's origin (where you will update the context state) and the component where you need to use it (which will re-render when the context state changes).
I could provide a more practical answer if you provided us with more information as to where the component using the list is located and how it uses it.

How to pass an Array from Child component to Parent component using hooks in react

I am working on a React project I am trying to pass a data from Child component to Parent component, But I don't know how to pass data from Child component to Parent component.
This is App.js
import React from 'react';
import './App.css';
import Parent from './Parent/Parent';
function App() {
return (
<div className="container">
<div className='row'>
<div className='col-12'>
<Parent></Parent>
</div>
</div>
</div>
);
}
export default App;
This is Parent.js
import React, { useState } from 'react';
import './Parent.css';
import Child from '../Child/Child';
const Parent = () => {
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div className='one'>
<Child></Child>
</div>
</div>
</div>
</div>
)
}
export default Parent
This is Child.js
import React from 'react';
import './Child.css';
const Child = () => {
const students = ['Jasmine', 'Stella']
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
</div>
</div>
</div>
)
}
export default Child
You can pass the data from Child to Parent by calling a function passed from Parent with the data you want to send as a parameter - like an event handler callback.
Let's say if you want to send students of your Child component to Parent when you click on an element:
const Parent = () => {
const onUpdate = (data) => {
// use the data
};
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div className='one'>
<Child update={onUpdate}></Child>
</div>
</div>
</div>
</div>
)
}
const Child = ({ update }) => {
const students = ['Jasmine', 'Stella']
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<button click={() => update(students)} />
</div>
</div>
</div>
)
}
But if you have to pass data between components nested deeply, you should consider to use Redux or Context.
To do this, You have two easiest ways,
Use React context
Use React prop callback
I suggest you use the first way and here is an example of implementing the redux context feature into your app based on your question's codes.
Demo

Resources