I'm trying to map an array that is the child of JSON objects found in the parent map. I'm still learning JSX and not sure if I can map within a JSX element, but it doesn't appear that my current solution is working because the object isn't rendering and there aren't errors appearing in my console that indicate any issue.
Here is the JSON Object:
[
{
"blogIdHash": "Zb2q97rX5n",
"title": "This is a test",
"discovery": "* Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris bibendum porta felis, vel varius ligula venenatis eget.\r\n\r\n* Quisque placerat, arcu placerat tincidunt dapibus, justo sapien accumsan lorem, vitae vulputate orci eros sollicitudin nisi. Vivamus dignissim lectus id tincidunt viverra. \r\n\r\n* **Suspendisse ut tempor magna**, et mattis augue. Quisque pretium dui sollicitudin blandit maximus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, \r\n\r\nper inceptos himenaeos. Quisque mattis lacinia felis eget sagittis. Quisque sed eros scelerisque",
"created_at": "2017-09-01T11:46:31.914Z",
"updated_at": "2017-09-01T12:14:59.375Z",
"blog_comments": [
{
"blogIdHash": "Zb2q97rX5n",
"blogCommentId": 9,
"comment": "Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur porta, eros vitae laoreet pharetra, neque dolor facilisis augue, elementum maximus sapien tortor nec sem. Sed eget est sed felis tincidunt congue. Sed blandit neque vitae tellus interdum, non gravida tortor venenatis.",
"userId": 237,
"created_at": "2017-09-01T11:54:49.089Z",
"updated_at": "2017-09-01T11:54:49.089Z",
},
{
"blogIdHash": "Zb2q97rX5n",
"blogCommentId": 10,
"comment": "Sed laoreet felis ac interdum faucibus. Pellentesque non purus commodo, faucibus magna ac, pharetra urna. Sed sapien eros, efficitur in dui venenatis, euismod mattis nisl. Cras a posuere turpis. Morbi suscipit mollis risus, convallis auctor urna. Nam tristique, ex quis sodales tempor, massa urna maximus odio,",
"userId": 240,
"created_at": "2017-09-01T11:59:12.573Z",
"updated_at": "2017-09-01T11:59:12.573Z",
}
]
}
]
Here is the component setup (JSON blob is being set through a parent component. BlogFeed renders with first mapped object set in BlogCard):
const BlogFeed = props => {
return (
<div>
{
props.blogs.map((blog, index) => {
return (
<BlogCard {...blog} key={blog.blogIdHash}>
return(
{ blog.blog_comments.map((comment, i) => <Comments {...comment} key={i} />)}
)
</BlogCard>
);
})
}
</div>
)
}
const BlogCard = props => {
return (
<div key={props.blogIdHash}>
<h4>{props.title}</h4>
<p>{props.discovery}</p>
</div>
)
}
const Comments = props => {
return (
<div key={props.blogCommentId}>
<h4>{props.comment}</h4>
</div>
)
}
You need to specify in your BlogCard component where to render its children.
Like this:
const BlogCard = props => {
return (
<div>
<h4>{props.title}</h4>
<p>{props.discovery}</p>
{props.children} // its children
</div>
)
}
Also, you don't need the return inside the BlogCard component, map returns an array and that return will be pass in props.children along with the comments and show on your HTML as simple text.
You can check a working example here.
You can find more details about props.children here.
Related
i am trying to build cv maker web application.and i need to convert componet to pdf file.
here my code
const handelDownload = () => {
html2canvas(componentRef.current).then(function (canvas) {
const divImage = canvas.toDataURL("image/png");
const pdf = new jsPDF();
pdf.addImage(divImage, "PNG", 0, 0);
pdf.save("download.pdf");
});
};
return (
<>
<h1>hello world</h1>
<div ref={componentRef}>
<h1 className="text-4xl bg-red-500">My Component</h1>
<p className="text-lg">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel
ipsum et velit posuere tempus sed ac ex. Vestibulum ante ipsum primis
in faucibus orci luctus et ultrices posuere cubilia curae; Integer
eget augue faucibus, placerat leo vitae, dignissim mi. Fusce id nibh
id risus congue consequat ac ut libero. Duis ut tincidunt turpis. Nam
scelerisque tortor in risus interdum consequat. Ut vel lectus sem.
Nulla hendrerit erat vel massa finibus, eget laoreet tellus ultrices.
Integer rhoncus lectus quis libero imperdiet, et viverra turpis
fermentum. Donec ullamcorper nisl eget felis dictum, at suscipit dolor
viverra. Etiam ullamcorper sem sit amet ante bibendum iaculis.
</p>
</div>
</>
problem is qulity of pdf is wrost and elements are not in the same position in the PDF as they are in the original component.
i also try reactpdf.
I am unable to read the HTML tags used in content of JSON file in my react app..
The JSON file :
[{
"_id": 9,
"title":"Text 9",
"subheader":"Dummy header 9",
"images": "images/four-1.png",
"imagesmob" : "images/four-1.webp",
"content":"<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent nec velit consectetur, pretium risus vel, eleifend tortor. Integer enim nulla, iaculis sit amet leo vel, sagittis maximus leo. Aliquam semper sapien bibendum nulla consectetur, ut eleifend arcu accumsan. Duis consequat diam sed dolor convallis semper. Ut justo mauris, accumsan non tempus ut, ultrices at tellus. Quisque a sapien urna. Maecenas tempor consequat sollicitudin. Nullam volutpat a eros sit amet vestibulum. Cras sollicitudin vitae urna nec varius. Etiam nec facilisis urna.</p> <p>Donec ut dui condimentum, tincidunt tellus vitae, interdum lorem. Phasellus eget pretium enim. Morbi accumsan turpis vitae turpis venenatis ullamcorper. Proin pretium nisi nec nulla faucibus, a hendrerit turpis malesuada. Nullam id faucibus metus, id faucibus metus. Donec et massa suscipit, congue tortor non, ultricies turpis. Aliquam venenatis massa velit, id ornare ante efficitur vitae. Vivamus id dui tortor. Pellentesque sem mi, bibendum a orci hendrerit, mollis eleifend eros. Nunc sodales orci purus. Vivamus molestie porta egestas. <p>Suspendisse convallis mi ullamcorper, dapibus nisi a, semper felis. Praesent ut lacus eu neque vestibulum efficitur.<\/p> Sed dolor magna, mattis a ultricies vel, <b>tincidunt<\/b> eget enim.<\/p>"
}
]
The react file
<Card variant="outlined" sx={{ maxWidth:345, borderRadius: '11px' }} elevation={3}>
<CardMedia
component="img"
height="194"
image={welcom.images}
alt="Home Page"
/>
<CardHeader
titleTypographyProps={{fontSize: 18, fontWeight: 'bold', color: 'purple' }}
title = {welcom.title}
subheader = {welcom.subheader}
/>
<CardContent>
<div>{welcom.content}</div>
</CardContent>
</Card>
In this when I am trying to read content from the json file , i am unable to get the text which is bold or paragraphs are also not coming. Any help.
You cannot render the raw html in React. For that you can use the dangerouslySetInnerHTML attribute, but you should be careful before using this attribute. As per reactjs document,
dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.
I have created based on your code.
I'm working on a new project, to build a React frontend for a Drupal 8 backend. When I issue a jsonapi query, like:
http://test.site/jsonapi/node/unit_descriptor/a95f6031-032d-4df0-83d3-42c2b6cc2f91
I get the following raw result:
"jsonapi": {
"version": "1.0",
"meta": {
"links": {
"self": {
"href": "http://jsonapi.org/format/1.0/"
}
}
}
},
"data": {
"type": "node--unit_content",
"id": "a95f6031-032d-4df0-83d3-42c2b6cc2f91",
"links": {
"self": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91?resourceVersion=id%3A250"
}
},
"attributes": {
"drupal_internal__nid": 221,
"drupal_internal__vid": 250,
"langcode": "en",
"revision_timestamp": "2020-03-21T18:18:01+00:00",
"revision_log": null,
"status": true,
"title": "Professional Practice",
"created": "2020-03-21T18:18:01+00:00",
"changed": "2020-03-26T17:42:21+00:00",
"promote": false,
"sticky": false,
"default_langcode": true,
"revision_translation_affected": true,
"path": {
"alias": null,
"pid": null,
"langcode": "en"
},
"field_intro": {
"value": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus sit amet tortor varius, luctus urna vel, consequat leo. Cras vulputate neque et sollicitudin rhoncus. Curabitur sed justo eros. Donec id odio blandit, aliquet augue id, porttitor est. Nullam molestie est nec lacus pretium blandit et ut risus. Vivamus suscipit tellus pharetra commodo gravida. Nam nec ex at massa finibus consectetur vehicula id urna. Phasellus nec porta quam, et sodales sapien. Integer id purus luctus, ornare eros a, pellentesque ligula. Donec nisl mi, consequat eget ligula nec, pharetra ultrices tortor. Duis dapibus egestas convallis.</p>\r\n\r\n<p>Nunc quam erat, accumsan eu odio iaculis, mollis congue ante. Vivamus auctor, sem ac imperdiet pellentesque, ligula ex fringilla nunc, et posuere massa nisi in arcu. Nam lacinia vel diam ac auctor. Aliquam mollis odio non neque aliquam rhoncus. Aliquam pellentesque dictum tincidunt. Donec interdum purus eu urna venenatis, eu sagittis risus viverra. Nam dictum at enim vitae tincidunt. Morbi pulvinar, risus eget venenatis tincidunt, mi velit molestie ligula, ac cursus enim dui in neque.</p>\r\n\r\n<p>Nulla facilisi. Sed malesuada imperdiet feugiat. Sed et tempus justo. In non erat ut enim consectetur porta. Vestibulum erat orci, congue vitae diam at, feugiat volutpat mauris. Phasellus viverra nisl eget nulla laoreet, id efficitur felis rhoncus. Quisque imperdiet, massa a tincidunt egestas, lectus urna auctor mi, quis dapibus risus purus et sem. Donec varius varius justo id luctus. Morbi nibh nibh, suscipit at pharetra non, tristique ac felis. Phasellus eu leo turpis. Suspendisse ac mattis velit. Mauris rhoncus nulla lectus, in sodales nulla congue a. Suspendisse euismod neque diam, vel tincidunt ex rhoncus in. Donec massa orci, tincidunt in malesuada eu, condimentum vel purus. Maecenas dapibus nulla magna, quis facilisis justo varius sit amet.<br />\r\n </p>\r\n",
"format": "full_html",
"processed": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus sit amet tortor varius, luctus urna vel, consequat leo. Cras vulputate neque et sollicitudin rhoncus. Curabitur sed justo eros. Donec id odio blandit, aliquet augue id, porttitor est. Nullam molestie est nec lacus pretium blandit et ut risus. Vivamus suscipit tellus pharetra commodo gravida. Nam nec ex at massa finibus consectetur vehicula id urna. Phasellus nec porta quam, et sodales sapien. Integer id purus luctus, ornare eros a, pellentesque ligula. Donec nisl mi, consequat eget ligula nec, pharetra ultrices tortor. Duis dapibus egestas convallis.</p>\n\n<p>Nunc quam erat, accumsan eu odio iaculis, mollis congue ante. Vivamus auctor, sem ac imperdiet pellentesque, ligula ex fringilla nunc, et posuere massa nisi in arcu. Nam lacinia vel diam ac auctor. Aliquam mollis odio non neque aliquam rhoncus. Aliquam pellentesque dictum tincidunt. Donec interdum purus eu urna venenatis, eu sagittis risus viverra. Nam dictum at enim vitae tincidunt. Morbi pulvinar, risus eget venenatis tincidunt, mi velit molestie ligula, ac cursus enim dui in neque.</p>\n\n<p>Nulla facilisi. Sed malesuada imperdiet feugiat. Sed et tempus justo. In non erat ut enim consectetur porta. Vestibulum erat orci, congue vitae diam at, feugiat volutpat mauris. Phasellus viverra nisl eget nulla laoreet, id efficitur felis rhoncus. Quisque imperdiet, massa a tincidunt egestas, lectus urna auctor mi, quis dapibus risus purus et sem. Donec varius varius justo id luctus. Morbi nibh nibh, suscipit at pharetra non, tristique ac felis. Phasellus eu leo turpis. Suspendisse ac mattis velit. Mauris rhoncus nulla lectus, in sodales nulla congue a. Suspendisse euismod neque diam, vel tincidunt ex rhoncus in. Donec massa orci, tincidunt in malesuada eu, condimentum vel purus. Maecenas dapibus nulla magna, quis facilisis justo varius sit amet.<br />\n </p>\n"
},
"field_unit_code": null
},
"relationships": {
"node_type": {
"data": {
"type": "node_type--node_type",
"id": "ded1db75-f372-47cc-baba-5244e2571aa0"
},
"links": {
"related": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91/node_type?resourceVersion=id%3A250"
},
"self": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91/relationships/node_type?resourceVersion=id%3A250"
}
}
},
"revision_uid": {
"data": {
"type": "user--user",
"id": "c899de1e-9950-40b4-b879-635b63e14724"
},
"links": {
"related": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91/revision_uid?resourceVersion=id%3A250"
},
"self": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91/relationships/revision_uid?resourceVersion=id%3A250"
}
}
},
"uid": {
"data": {
"type": "user--user",
"id": "c899de1e-9950-40b4-b879-635b63e14724"
},
"links": {
"related": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91/uid?resourceVersion=id%3A250"
},
"self": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91/relationships/uid?resourceVersion=id%3A250"
}
}
},
"field_lo_ec_ac": {
"data": [
{
"type": "paragraph--lo_ec_ac",
"id": "286b325c-7538-4a39-8a94-cfc19faf1b93",
"meta": {
"target_revision_id": 3
}
},
{
"type": "paragraph--lo_ec_ac",
"id": "d18bdb1d-483d-418c-8bfd-b316afe799ac",
"meta": {
"target_revision_id": 5
}
},
{
"type": "paragraph--lo_ec_ac",
"id": "5de14184-0933-456a-b69a-6075021182dd",
"meta": {
"target_revision_id": 7
}
},
{
"type": "paragraph--lo_ec_ac",
"id": "44a82b1f-f79e-44af-9d10-5bda16d5be30",
"meta": {
"target_revision_id": 9
}
}
],
"links": {
"related": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91/field_lo_ec_ac?resourceVersion=id%3A250"
},
"self": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91/relationships/field_lo_ec_ac?resourceVersion=id%3A250"
}
}
},
"field_parent_unit": {
"data": [
{
"type": "node--unit_descriptor",
"id": "d79d581b-9b8d-42de-8dbd-82ecbf94287c"
}
],
"links": {
"related": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91/field_parent_unit?resourceVersion=id%3A250"
},
"self": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91/relationships/field_parent_unit?resourceVersion=id%3A250"
}
}
}
}
},
"links": {
"self": {
"href": "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91"
}
}
}
But, when I run this code in my React:
super()
this.state={
loading:false,
unitContent:{}
}
}
componentDidMount(){ axios.get(`http://test.site/jsonapi/node/unit_content/${this.props.id}`)
.then(
response =>{
const unitContent = response.data;
this.setState({unitContent})
}, error => {
console.log(error)
}
)
}
...
console.log(this.state.UnitContent)
And, then run console.log(this.state.unitContent) I get four results (two are null, and two are the same)
[Log] {}
[Log] {}
[Log] {jsonapi: Object, data: Object, links: {self: {href: "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91"}}}
[Log] {jsonapi: Object, data: Object, links: {self: {href: "http://test.site/jsonapi/node/unit_content/a95f6031-032d-4df0-83d3-42c2b6cc2f91"}}}
Why am I getting two empty results, and two duplicates? There is only one record, so shouldn't there only be one return?
Any help, greatly appreciated (as I would then be able to stop including a ton of 'if' to deal with the blanks).
Thanks
I have the following code to add to a variable every time the mouse has reached the end of the page :
const [number, setNum] = React.useState(5);
const addUp = () => {
setNum(number + 1);
}
const handleScroll = cb => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) cb();
};
React.useEffect(() => {
window.addEventListener("scroll", handleScroll(addUp));
}, [number]);
return (
<div className="App">
{console.log(number)}
sadly the code does not add to its existing value or with a little change to useEffect dependencies I end up in an infinite loop.
How can I add to my state by scrolling to the end of the page ?
the full code can be found at https://codesandbox.io/s/laughing-tree-pw6co
You can try something like the following. Don't add any dependencies for the useEffect() that creates the window event-listener. Anytime your component re-renders that will create a brand-new event listener on top of the one that already exists. You only want that useEffect() to execute once.
To assist you, you can add a second useState() to keep track of the scroll position. true if they are at the bottom, false otherwise. We'll call this endReached.
Then use a second useEffect() to verify the value of endReached, if true then increase number.
See working sandbox: http://codesandbox.io/s/youthful-hofstadter-h362t
App.js
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const myref = React.useRef(0);
const [number, setNum] = React.useState(5);
const [endReached, setEndReached] = React.useState(false);
const handleScroll = () => {
if (
window.scrollY + window.innerHeight >= document.body.offsetHeight &&
!endReached
) {
setEndReached(true);
} else {
setEndReached(false);
}
};
React.useEffect(() => {
if (endReached) {
setNum(number + 1);
}
}, [endReached]);
React.useEffect(() => {
window.addEventListener("scroll", () => handleScroll());
}, []);
return (
<div className="App">
<h1>number is {number}</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tristique
consequat imperdiet. Nulla vitae dolor in nisl fermentum egestas ut ac
nulla. Quisque aliquam libero sit amet neque ullamcorper molestie.
Phasellus massa ligula, rhoncus non consectetur sit amet, consequat eu
leo. Proin nec gravida sapien. Proin convallis malesuada est, nec
tincidunt massa. Quisque sit amet augue molestie, convallis purus quis,
porttitor quam. Duis iaculis ultrices ipsum a egestas. Duis pulvinar
urna sit amet egestas rutrum. Praesent sed consectetur felis. Nulla
massa libero, iaculis tempor porta ornare, hendrerit eu est. Praesent
tempor consequat nibh, in aliquam quam laoreet ut. Sed laoreet congue
urna id feugiat. Etiam egestas gravida dictum. Vestibulum nec sapien
turpis. In hac habitasse platea dictumst. Vestibulum odio turpis,
tincidunt sit amet ultricies at, interdum quis massa. Ut vestibulum quis
tortor viverra consequat. Phasellus ligula erat, efficitur non justo in,
pretium tempor nibh. Aliquam fringilla fermentum consectetur. Nunc
cursus convallis posuere. Pellentesque ac quam a mauris tempus dapibus
ut at quam. In vel tellus in eros elementum bibendum at mollis metus.
Fusce venenatis aliquet magna, non viverra odio dapibus vitae. Etiam
orci metus, consectetur ut enim at, tristique pellentesque augue. Sed eu
cursus metus. Maecenas imperdiet ultricies hendrerit. Maecenas porta
varius ipsum, a convallis magna pharetra ac. Sed sit amet dolor quis mi
luctus auctor. Mauris finibus, purus in dictum suscipit, nibh lacus
consequat orci, id ornare tellus lectus non urna. Nulla est neque,
sagittis at lacinia id, pulvinar quis sem. In hac habitasse platea
dictumst. Aenean vel porta ante, quis pulvinar velit. Etiam at mollis
sapien. Ut tristique pretium nisi, in tincidunt nisl pulvinar nec. Ut ac
ultricies erat, nec maximus neque. Vestibulum ante ipsum primis in
faucibus orci luctus et ultrices posuere cubilia Curae; Integer
vehicula, magna non aliquam sagittis, ex sapien interdum magna, vitae
gravida arcu nisi varius nunc. Nunc molestie ante a imperdiet finibus.
Aenean pellentesque rhoncus tincidunt. Suspendisse potenti. Nullam
dictum nibh vel sem ultrices, at lacinia sem cursus. Etiam dignissim
porta nulla a commodo. Nulla facilisi. Quisque non erat lectus.
Suspendisse a justo mi. Suspendisse ut sem et magna vulputate facilisis.
Morbi rutrum ornare tristique. Nam facilisis et urna ut fringilla. Etiam
pretium augue eu lorem mattis vestibulum. Nulla iaculis lorem ultricies
justo varius, id aliquet arcu fringilla. Nunc vehicula velit id nisi
imperdiet, ut lobortis arcu dignissim. Donec et orci iaculis, aliquet mi
quis, pellentesque elit. Aenean ipsum libero, molestie vitae libero eu,
mattis porta nulla. Duis vitae ornare turpis, eget lobortis enim. Cras
ut sagittis ipsum. Aenean luctus lacinia leo, a luctus augue pharetra
nec. Nulla blandit in est id cursus.
</p>
<button onClick={() => setNum(myref.current.value)}>Change</button>
<br />
<input ref={myref} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I create this code:
import React from 'react'
import { range } from 'lodash'
const DIV_NUMBER = 5
export default class App extends React.Component {
constructor(props) {
super(props)
this.divs = []
}
handleScroll = divIdx => () => {
const divRef = this.divs[divIdx]
const left = divRef.scrollLeft
const top = divRef.scrollTop
this.divs.forEach(div => (div.scrollLeft = left))
this.divs.forEach(div => (div.scrollTop = top))
}
render() {
return (
<div style={{ border: '1px solid tomato' }}>
{range(DIV_NUMBER).map(i => {
return (
<div
key={i}
ref={divElem => (this.divs[i] = divElem)}
onScroll={this.handleScroll(i)}
style={{
width: 300,
height: 100,
margin: '2px',
overflow: 'auto',
border: '1px solid black',
}}
>
<div
style={{
width: 500,
height: 400,
}}
>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Scelerisque eu ultrices vitae auctor eu
augue ut lectus. In fermentum et sollicitudin ac orci. Velit sed ullamcorper morbi
tincidunt ornare. Auctor eu augue ut lectus arcu bibendum. Non nisi est sit amet.
Facilisis magna etiam tempor orci eu lobortis. Et tortor at risus viverra adipiscing
at in tellus integer. Lacus luctus accumsan tortor posuere ac ut consequat semper
viverra. Fermentum dui faucibus in ornare quam viverra orci sagittis. Porttitor eget
dolor morbi non. Pulvinar pellentesque habitant morbi tristique senectus et.
Tincidunt eget nullam non nisi est sit amet facilisis magna. Purus semper eget duis
at tellus at urna condimentum. Ipsum dolor sit amet consectetur adipiscing. Sit amet
aliquam id diam maecenas ultricies mi eget mauris. Faucibus scelerisque eleifend
donec pretium vulputate sapien nec sagittis. Tristique senectus et netus et
malesuada fames ac turpis. Egestas integer eget aliquet nibh. Enim ut tellus
elementum sagittis vitae. Urna condimentum mattis pellentesque id nibh tortor id
aliquet. Magna eget est lorem ipsum dolor. Felis imperdiet proin fermentum leo vel
orci porta. Eget egestas purus viverra accumsan in nisl nisi. Adipiscing commodo
elit at imperdiet. Facilisis magna etiam tempor orci eu lobortis. Volutpat est velit
egestas dui id ornare arcu odio. Praesent elementum facilisis leo vel fringilla.
Laoreet non curabitur gravida arcu ac tortor dignissim convallis aenean. Sodales ut
etiam sit amet nisl. Turpis massa tincidunt dui ut ornare. Viverra mauris in aliquam
sem fringilla ut morbi tincidunt augue.
</div>
</div>
)
})}
</div>
)
}
}
It works.
It creates 5 div elements, scrolling one of them, all the div scroll togheter. I use React references to do that.
What I would like to do now is creates a component that abstracts this logic.
I imagine something like that:
<ScrollDivs>
{range(DIV_NUMBER).map(i => {
return (
<div
key={i}
style={{
width: 500,
height: 400,
}}
>
all the text...
</div>
)
})}
</ScrollDivs>
So a magic component ScrollDivs that deals with logic.
Who uses this component does not have to worry about how it is done, he just needs to wrap the divs that wants to be able to scroll together inside this component.
How can I do? I don't know where to start.
Any help is appreciate
React.Children.map can help you to iterate over props.children and React.cloneElement can help with passing new props to children:
export default class ScrollDivsSync extends React.Component {
divs = [];
handleScroll = e => {
const { scrollTop, scrollLeft } = e.target;
this.divs.forEach(div => {
div.scrollLeft = scrollLeft;
div.scrollTop = scrollTop;
});
};
render() {
const { children } = this.props;
let i = 0;
const enhancedChildren = React.Children.map(children, child =>
React.cloneElement(child, {
onScroll: this.handleScroll,
ref: divElem => (this.divs[i++] = divElem)
})
);
return enhancedChildren;
}
}
This is a CodeSandbox with the example