Using React-Dom's render more than once - reactjs

Is it at all possible to use react-dom's render more than once in a react spa, in particular in a nested child component? For example:
index.jsx:
import React from 'react';
import { render } from 'react-dom';
import sampleComponent from './sampleComponent';
render(<SampleComponent />, document.getElementById('app'));
sampleComponent.jsx:
import React from 'react';
import { render } from 'react-dom';
const SampleComponent = () => (
<div>
<h1>hello world</h1>
<div id="foo" />
</div>
);
export default SampleComponent;
render(<h1>it's me again</h1>, document.getElementById('foo'));

To use render more than once is a complicated way.
You don't need that.
You already create a valid component. Just wrap it into another and use more then once. En example:
const SampleComponent = () => (
<div>
<h1>hello world</h1>
<div id="foo" />
</div>
);
const WrapperComponent = () => (
<div>
<SampleComponent />
<SampleComponent />
</div>
);
export default WrapperComponent;

Related

Having a problem with the state not being transferred to another component

I am having a problem that the value made by one component cannot be delivered to another component. I made a state in the top component and I think I connected it well. But the desired array made of state is empty. Sorry for the long code to ask.
The code below is the top component, and InCart is the state that I'm having issues with.
App.js:
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Site from './Site/Site';
import { useState } from 'react';
import RealCart from './RealCart/RealCart';
function App() {
const [Inproducts,setInproducts] = useState([])
const [InCart, setInCart] = useState([]);
return (
<BrowserRouter>
<Routes>
<Route path='/realCart' element={<RealCart InCart={InCart} setInCart={setInCart}/>} />
<Route path='/loginHome' element={<Site InCart={InCart} setInCart={setInCart} Inproducts={Inproducts} setInproducts={setInproducts}/>}/>
</Routes>
</BrowserRouter>
);
}
export default App;
There are many components connected in the middle, so I omitted it, but the props are connected as well. And I got the json file from here.
Section5Bottom.jsx:
import axios from 'axios';
import React, { useEffect } from 'react';
import "../section5.css";
import Section5Card from './Section5Card';
function Section5Bottom({Inproducts, setInproducts, InCart, setInCart}) {
useEffect (()=> {
axios.get("/data/products.json").then((data)=>{
setInproducts(data.data.products);
});
},[setInproducts]);
return (
<div id='Section5Bottom'>
{
Inproducts.map((product)=>{
return <Section5Card key={`key-${product.id}`} product={product} InCart={InCart} setInCart={setInCart}/>
})
}
</div>
)
}
export default Section5Bottom;
When I clicked the icon below the file, I used the InCart made in App.js to put the array value of the selected card in the array. If I check the console here, the array is good as shown in this photo.
Section5Card.jsx:
import '../section5.css';
import {FaCartPlus} from 'react-icons/fa';
import { useDispatch } from 'react-redux';
import './card.css';
function Section5Card({product, InCart, setInCart}) {
const dispatch = useDispatch();
const handleCart = () => {
const cartItem = {
id : product.id,
image : product.image,
provider : product.provider,
price : product.price,
name : product.name
}
setInCart([...InCart, cartItem])
}
return (
<div>
<div id='CardWrap'>
<div>
<img id='Section5CardImg' src={product.image} />
</div>
//************************************
<div>
<FaCartPlus size='20' style={{color:'black', position:'relative', top:'124px', left:'130px', cursor:'pointer'}} onClick={()=>{dispatch({type:"ADD"}); handleCart()}} />
</div>
//*************************************
<div id='CardBot'>
<div id='CardBotBPrice'>
₩{product.price}
</div>
<div id='CardBotTag'>
{product.people?
<span id='CardBotTagPeople'>
{product.people}명
</span>:
<>
<span id='CardBotTagSale'>
{product.sale}
</span>
</>}
</div>
</div>
</div>
</div>
)
}
export default Section5Card;
And the below file is the one I wish to bring up in the InCart state. But even if I check with the console, the array is empty as shown below:
RealCart.jsx:
import React from 'react'
import Top from '../Site/Header/Top'
import Navi from '../Site/Header/Navi/Navi'
import Cart from './Components/Cart';
import CartHeader from './Components/CartHeader';
function RealCart(InCart, setInCart) {
console.log(InCart)
return (
<div>
<Top />
<Navi />
<Cart />
<CartHeader />
</div>
)
}
export default RealCart;
In your RealCart.jsx file you have to wrap your props with {} and it will be like
function RealCart({InCart, setInCart}) {
console.log(InCart)
return (
<div>
<Top />
<Navi />
<Cart />
<CartHeader />
</div>
)
}

How to pass prop from one component to another?

I need to pass prop called name from one React component to another, but something goes wrong. Could you tell me how to do it right?
Thanks in advance
import React from 'react';
export class Greeting extends React.Component {
render() {
return (
<h1>Hello World and {this.props.name}</h1>
)
}
}
import React from 'react';
import ReactDOM from 'react-dom';
import Greeting from './Greeting';
function App() {
return (
<div>
<Greeting name='Alex' />;
<h2> Welcome, {Greetings.props.name} </h2>
</div>
);
}
export default App;
two things:
looks like you are mixing class and functional components, i recommend going for functional as its more common now. in that case the Greeting will look like this:
export function Greeting(props) {
return (
<h1>Hello World and {props.name}</h1>
)
}
you are passing the prop the the component, but you cant access it from its parent. you can create another variable for that:
const greetingName = "Alex";
function App() {
return (
<div>
<Greeting name={greetingName} />;
<h2> Welcome, {greetingName} </h2>
</div>
);
}
In Greeting.js you have missed parameter
App.js
import React, { useState } from 'react';
import Greeting from './Greeting';
const App = () => {
const [name, setName] = useState("")
return (
<div>
<Greeting name="Alex" />
</div>
)
}
export default App
Greeting.js
import React from 'react'
const Greeting = (props) => {
return (
<div>
<h1>Hello World and My name is {props.name}</h1>
</div>
)
}
export default Greeting

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>
</>
)

How to pass a dynamic value from one component to the other in React

I have a Navbar component with an anchor tag containing an onClick event. On click, a value (navvalue) is passed to the function Testfunction, which is a separate component. I want to import Testfunction into the Content component so that I can have access and display the value coming from Navbar (navvalue). How do I access “navvalue” in Content? This is an assignment in a react course I´m taking. I should use props. I´m not supposed to use either state or React Route since we haven´t reach those topics yet. Thank you for your help!
Here´s my code:
App.js
import "./styles.css";
import React from "react";
import Navbar from "./Navbar";
import Content from "./Content";
import Testfunction from "./Testfunction";
export default function App() {
return (
<div className="App">
<Navbar onPageChange={Testfunction} />
<Content />
</div>
);
}
Navbar.js
import React from "react";
const Navbar = (props) => {
const navvalue = "Nav Value";
return (
<a
className="nav-link active text-uppercase"
aria-current="page"
href="#"
onClick={() => props.onPageChange(navvalue)}
>
{navvalue}
</a>
);
};
export default Navbar;
Testfunction.js
const Testfunction = (navvalue) => {
return navvalue;
};
export default Testfunction;
Content.js
import React from "react";
import Testfunction from "./Testfunction";
const Content = () => {
const navvalue = Testfunction();
return (
<p>Here´s the content. Insert value coming from Navbar here: {navvalue}</p>
);
};
export default Content;
To share some state in both <Navbar /> and <Content /> you can put state to their parent -> App. Also to <Navbar /> we pass setter function to update state which is in parent. So it can be like this:
import React from "react";
export default function App() {
const [navValue, setNavValue] = React.useState();
return (
<div className="App">
<Navbar setNavValue={setNavValue} />
<Content navValue={navValue} />
</div>
);
}
const Navbar = ({ setNavValue }) => {
const value = "Nav Value";
return <button onClick={() => setNavValue(value)}>{value}</button>;
};
const Content = ({ navValue }) => {
return (
<p>Here´s the content. Insert value coming from Navbar here: {navValue}</p>
);
};

react - children component not showing

I'm trying to insert a child component inside another child component, but my code is not working. Following codes are the structure i'm trying to build.
const AddProductPage= () => {
return (
<PageTemplate>
<ProductTemplate>
<AddProduct />
</ProductTemplate>
</PageTemplate>
);
};
const PageTemplate= ({children}) => {
return (
<div className={cx('pagetemplate')}>
<HeaderContainer />
<main>
{children}
</main>
<Footer />
</div>
);
};
class ProductTemplate extends Component {
render() {
return (
<div className={cx('product-template')}>
...
<div className={cx('display')}>
{this.props.children}
</div>
</div>
);
}
}
class AddProduct extends Component {
render() {
return (
<div className={cx('addproduct')}>
addproduct
</div>
);
}
}
I'm trying to insert AddProduct component in ProductTemplate component as a child, which is inserted in PageTemplate component as a child. AddProductPage, however, is not showing AddProduct component. I'd be grateful if anyone can help.
I've run your code. May be you'r missing default export statements.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import AddProductPage from './AddProductPage';
ReactDOM.render(<AddProductPage />, document.getElementById('root'));
AddProductPage.js
import React from 'react';
import PageTemplate from './PageTemplate';
import ProductTemplate from './ProductTemplate';
import AddProduct from './AddProduct';
const AddProductPage= () => {
return (
<PageTemplate>
<ProductTemplate>
<AddProduct />
</ProductTemplate>
</PageTemplate>
);
};
export default AddProduct;
PageTemplate.js
import React from 'react';
const PageTemplate= ({children}) => {
return (
<div>
<main>
{children}
</main>
</div>
);
};
export default PageTemplate;
ProductTemplate.js
import React,{Component} from 'react';
class ProductTemplate extends Component {
render() {
return (
<div>
<div>
{this.props.children}
</div>
</div>
);
};
};
export default ProductTemplate;
AddProduct.js
import React, {Component} from 'react';
class AddProduct extends Component {
render() {
return (
<div>
addproduct
</div>
);
};
};
export default AddProduct;
Output is this :
addproduct
Here`s a Fiddle of your code
Works Fine!. I have removed cx API. I suppose the problem might be with className resolution. Check in the dom hierarchy weather the Children DOM Node exists and they have received their respective classnames.
const PageTemplate= ({children}) => {
return (
<div className={'pagetemplate'}>
<HeaderContainer />
<main>
{children}
</main>
<Footer />
</div>
);
};

Resources