I'm need justify a text and my code isn't work correctly.
import React from "react"
import { ScrollView, StyleSheet, View, WebView } from "react-native"
export default class App extends React.Component {
render() {
return (
<ScrollView style={styles.container}>
<WebView
source={{
html:
"<style>p{text-align:justify}</style>" +
"<p>" +
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus commodo tortor ut ipsum pharetra sodales. Praesent sed diam non lacus convallis dapibus. Sed vulputate erat risus, ac hendrerit eros egestas id. Etiam pellentesque auctor ipsum, non cursus nisi gravida sed. Ut eget pretium risus. Curabitur a lectus odio. Etiam felis urna, pharetra ut odio in, tristique suscipit tortor. Cras vitae risus odio. Etiam a leo elit. Duis molestie fermentum mi vitae pretium. Morbi luctus semper quam, et suscipit nisi convallis dictum. Fusce sit amet est dapibus, interdum ante non, lacinia metus. Donec at nulla non ante consectetur vulputate. Cras tristique porttitor ligula quis posuere. Integer nec laoreet felis, at tempor leo. Ut et convallis quam." +
"</p>"
}}
/>
</ScrollView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
margin: 20
}
})
The text isn't showed in the screen.
I'm try execute the code in a Android device.
Try removing the scrollView component, and putting the style in the Webview.
Here is an example:
https://snack.expo.io/SJQ5Mf9ym
Related
For better web app performance, I am showing different images on mobile and desktop due to resolution. The data is getting loaded from 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 code file is :
<Card variant="outlined" sx={{ maxWidth:345, borderRadius: '11px' }} elevation={3}>
<CardMedia
component="img"
height="194"
image={welcom.images}
alt="Home Page"
sx={{display:{xs:'none', sm:'none',md:'block'}}}
/>
<CardMedia
component="img"
height="194"
image={welcom.imagesmob}
alt="Home Page"
sx={{display:{xs:'block', sm:'block',md:'none'}}}
/>
<CardHeader
titleTypographyProps={{fontSize: 18, fontWeight: 'bold', color: 'purple' }}
title = {welcom.title}
subheader = {welcom.subheader}
/>
<CardContent>
<div>{welcom.content}</div>
</CardContent>
</Card>
In tthis I want to load images for mobile in CardMedia, when I used display none and made other cardmedia for mobile, the image used for desktop is also getting loaded. I dont want the image for desktop to be loaded when on mobile. As this affect the website performance.
Any help will be appreciated. Thanks
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 am having trouble getting the Material UI Menu to work with React Table#v6.
I want to be able to right-click anywhere in the table (row, td) and show a context menu. This part is working.
But I also want to be able to continuously right-click other locations in the table and always show the context menu the cursor location. This is not working. Currently, you have to click-away to close the menu and then right-click again to re-open the menu.
In the Material UI demo this is working fine:
https://material-ui.com/components/menus/#context-menu
I adopted the example above to work with React Table, but it's not quite working as expected.
My example adoption:
https://codesandbox.io/s/aged-leaf-0nf6b?file=/src/index.js
Any Ideas how to get this to work as in the example?
This is because you added onContextMenu props to Td, not the table container.
Move onContext Menu to container div, like this:
<div onContextMenu={(e) => {
e.preventDefault();
console.log("context menu");
this.setState({
mouseX: e.clientX - 2,
mouseY: e.clientY - 4
});
}}>
And it should work.
Enjoy!
I ended up creating a popper context menu to replicate all the material-ui behavior for menus.
import React from "react";
import Popper from "#material-ui/core/Popper";
import Typography from "#material-ui/core/Typography";
import MenuList from "#material-ui/core/MenuList";
import MenuItem from "#material-ui/core/MenuItem";
import Paper from "#material-ui/core/Paper";
import { makeStyles } from "#material-ui/core/styles";
import { ClickAwayListener, Fade } from "#material-ui/core";
/* copied from https://github.com/mui-org/material-ui/blob/v4.3.2/packages/material-ui/src/Menu/Menu.js#L21 */
const useMenuStyles = makeStyles({
/* Styles applied to the `Paper` component. */
paper: {
// specZ: The maximum height of a simple menu should be one or more rows less than the view
// height. This ensures a tapable area outside of the simple menu with which to dismiss
// the menu.
maxHeight: "calc(100% - 96px)",
// Add iOS momentum scrolling.
WebkitOverflowScrolling: "touch"
},
/* Styles applied to the `List` component via `MenuList`. */
list: {
// We disable the focus ring for mouse, touch and keyboard users.
outline: 0
}
});
export default function FakedReferencePopper() {
const [open, setOpen] = React.useState(false);
const [anchorEl, setAnchorEl] = React.useState<null | any>(null);
const handleClose = () => {
setOpen(false);
};
const handleContextMenu = (e) => {
e.preventDefault();
const { clientX, clientY } = e;
setOpen(true);
const virtualElement = {
getBoundingClientRect: () => ({
width: 0,
height: 0,
top: clientY,
right: clientX,
bottom: clientY,
left: clientX
})
};
setAnchorEl(virtualElement);
};
const id = open ? "faked-reference-popper" : undefined;
const menuClasses = useMenuStyles();
return (
<div>
<div onContextMenu={handleContextMenu}>
<Typography aria-describedby={id}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ipsum
purus, bibendum sit amet vulputate eget, porta semper ligula. Donec
bibendum vulputate erat, ac fringilla mi finibus nec. Donec ac dolor
sed dolor porttitor blandit vel vel purus. Fusce vel malesuada ligula.
Nam quis vehicula ante, eu finibus est. Proin ullamcorper fermentum
orci, quis finibus massa. Nunc lobortis, massa ut rutrum ultrices,
metus metus finibus ex, sit amet facilisis neque enim sed neque.
Quisque accumsan metus vel maximus consequat. Suspendisse lacinia
tellus a libero volutpat maximus. Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Nullam ipsum purus, bibendum sit amet
vulputate eget, porta semper ligula. Donec bibendum vulputate erat, ac
fringilla mi finibus nec. Donec ac dolor sed dolor porttitor blandit
vel vel purus. Fusce vel malesuada ligula. Nam quis vehicula ante, eu
finibus est. Proin ullamcorper fermentum orci, quis finibus massa.
Nunc lobortis, massa ut rutrum ultrices, metus metus finibus ex, sit
amet facilisis neque enim sed neque. Quisque accumsan metus vel
maximus consequat. Suspendisse lacinia tellus a libero volutpat
maximus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nullam ipsum purus, bibendum sit amet vulputate eget, porta semper
ligula. Donec bibendum vulputate erat, ac fringilla mi finibus nec.
Donec ac dolor sed dolor porttitor blandit vel vel purus. Fusce vel
malesuada ligula. Nam quis vehicula ante, eu finibus est. Proin
ullamcorper fermentum orci, quis finibus massa. Nunc lobortis, massa
ut rutrum ultrices, metus metus finibus ex, sit amet facilisis neque
enim sed neque. Quisque accumsan metus vel maximus consequat.
Suspendisse lacinia tellus a libero volutpat maximus. Lorem ipsum
dolor sit amet, consectetur adipiscing elit. Nullam ipsum purus,
bibendum sit amet vulputate eget, porta semper ligula. Donec bibendum
vulputate erat, ac fringilla mi finibus nec. Donec ac dolor sed dolor
porttitor blandit vel vel purus. Fusce vel malesuada ligula. Nam quis
vehicula ante, eu finibus est. Proin ullamcorper fermentum orci, quis
finibus massa. Nunc lobortis, massa ut rutrum ultrices, metus metus
finibus ex, sit amet facilisis neque enim sed neque. Quisque accumsan
metus vel maximus consequat. Suspendisse lacinia tellus a libero
volutpat maximus. Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Nullam ipsum purus, bibendum sit amet vulputate eget, porta
semper ligula. Donec bibendum vulputate erat, ac fringilla mi finibus
nec. Donec ac dolor sed dolor porttitor blandit vel vel purus. Fusce
vel malesuada ligula. Nam quis vehicula ante, eu finibus est. Proin
ullamcorper fermentum orci, quis finibus massa. Nunc lobortis, massa
ut rutrum ultrices, metus metus finibus ex, sit amet facilisis neque
enim sed neque. Quisque accumsan metus vel maximus consequat.
Suspendisse lacinia tellus a libero volutpat maximus. Lorem ipsum
dolor sit amet, consectetur adipiscing elit. Nullam ipsum purus,
bibendum sit amet vulputate eget, porta semper ligula. Donec bibendum
vulputate erat, ac fringilla mi finibus nec. Donec ac dolor sed dolor
porttitor blandit vel vel purus. Fusce vel malesuada ligula. Nam quis
vehicula ante, eu finibus est. Proin ullamcorper fermentum orci, quis
finibus massa. Nunc lobortis, massa ut rutrum ultrices, metus metus
finibus ex, sit amet facilisis neque enim sed neque. Quisque accumsan
metus vel maximus consequat. Suspendisse lacinia tellus a libero
volutpat maximus.
</Typography>
</div>
<Popper
id={id}
open={open}
anchorEl={anchorEl}
transition
placement="bottom-start"
>
{({ TransitionProps }) => (
<ClickAwayListener onClickAway={handleClose}>
<Fade {...TransitionProps}>
<Paper className={menuClasses.paper}>
<MenuList className={menuClasses.list} autoFocus>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</MenuList>
</Paper>
</Fade>
</ClickAwayListener>
)}
</Popper>
</div>
);
}
Here is codesandbox
https://codesandbox.io/s/popper-context-menu-t1u6r
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