How to append text to text area created in React JS? - javascript

I have the following code which creates a text area.
interface IReceiverProps {
receivedMessage: string;
topic: string;
}
export default class Receiver extends React.Component<IReceiverProps, {}> {
render() {
var textAreaStyle = {
width: 1300,
height: 450,
border: '3px solid #cccccc',
padding: '5px',
fontFamily: 'Tahoma, sans-serif',
overflow: 'auto',
marginLeft: '10px'
}
return (
<textarea style={textAreaStyle} value={this.props.receivedMessage}/>
);
}
}
This received message is passed by another component. How can I append the receivedMessage one below another in this text area? Any help would be much appreciated.

Use a state called textMessage.
constructor(props) {
super(props);
this.state = {
textMessage: props.receivedMessage
};
}
In componentWillReceiveProps, append to textMessage.
componentWillReceiveProps(nextProps) {
if (nextProps.receivedMessage !== this.props.receivedMessage) {
this.setState({
textMessage: `${this.state.textMessage}\n{nextProps.receivedMessage}`
});
}
}
Bind to textMessage.
<textarea style={textAreaStyle} value={this.state.textMessage} />

Related

Show/Hide React Component based on State

I am very new to React and am trying to create a page where clicking on the color square will show the hex code for that color. I've tried a bunch of different things and I can't figure out if my problem is in the event handling, in the state handling, both, or in something else altogether. I can get the hex code to either be there or not, but not have it change when I click.
Here is my main:
<main>
<h1>Dynamic Hex Code Display</h1>
<div id="container"></div>
<script type="text/babel">
class ColorSquare extends React.Component {
render() {
var blockStyle = {
height: 150,
backgroundColor: this.props.color,
};
return <div style={blockStyle} onClick = {this.props.onClick}></div>;
}
}
class HexDisplay extends React.Component {
render() {
var hexText = {
fontFamily: "arial",
fontWeight: "bold",
padding: 15,
margin: 0,
textAlign: "center",
};
var hexTextVis = {
...hexText,
visibility: "visible"
}
var hexTextInvis = {
...hexText,
visibility: "hidden"
}
var isVisible = this.props.isVisible;
if (isVisible) {
return <p style={hexTextVis}>{this.props.color}</p>;
} else {
return <p style={hexTextInvis}>{this.props.color}</p>;
}
}
}
class HexParent extends React.Component {
constructor(props) {
super(props);
this.state = {
isVisible: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
this.setState(currentVis => ({isVisible: !currentVis.isVisible}));
console.log(this.state);
console.log('clicking');
}
render() {
var fullBoxStyle = {
padding: 0,
margin: 10,
backgroundColor: "#fff",
boxShadow: "3px 3px 5px #808080",
boxRadius: "5px 5px",
height: 200,
width: 150,
};
var buttonStyle = {
width:150,
backgroundColor: this.props.color
}
return (
<div style={fullBoxStyle}>
<span onClick={(e) => this.handleClick()}>
<ColorSquare color={this.props.color} />
<span style={{
isVisible: this.state.isVisible ? "true" : "false",
}}>
<HexDisplay color={this.props.color} />
</span>
</span>
</div>
);
}
}
ReactDOM.render(
<div class="colorRow">
<HexParent color="#ba2c9d" />
<HexParent color="#2cba90" />
<HexParent color="#2c9dba" />
</div>,
document.querySelector("#container")
);
</script>
When the object is created, it's a hexTextVis object. When you click, isVisible changes, but it's still a hexTextVis object and so the render doesn't change. You could either do something like:
<HexDisplay visibility={state.isVisible}/>
or
{state.isVisible ? <div/> : <HexDisplay />}
style={{
isVisible: this.state.isVisible ? "true" : "false",
}}
There isn't a css property with this name. Perhaps you meant to use visibility?
style={{
visibility: this.state.isVisible ? "visible" : "hidden"
}}
Try wrapping the span and and using a ternary operator to render the span element, based on if the condition of isVisible is equal to true, otherwise it should not return anything
{this.state.isVisible && <span><HexDisplay /></span>}

In React SharePoint WebPart what are the differences between using 'html-react-parser' & using 'dompurify eslint-plugin-risxss' to securely show HTML

I am trying to build a React.js SharePoint modern web part, which have the following capabilities:-
Inside the Web Part settings page >> there are 2 fields named as "Who We Are" & "Our Value" which allow the user to enter HTML.
The web part will render 2 buttons "Who We Are" & "Our Value" >> and when the user clicks on any button >> a Popup will be shown with the entered HTML code in step-1
Something as follow:-
But to be able to render HTML code as Rich-Text inside my Web Part, i have to use the dangerouslySetInnerHTML attribute inside the .tsx file. as follow:-
import * as React from 'react';
import { useId, useBoolean } from '#fluentui/react-hooks';
import {
getTheme,
mergeStyleSets,
FontWeights,
Modal,
IIconProps,
IStackProps,
} from '#fluentui/react';
import { IconButton, IButtonStyles } from '#fluentui/react/lib/Button';
export const MYModal2 = (myprops) => {
const [isModalOpen, { setTrue: showModal, setFalse: hideModal }] = useBoolean(false);
const [isPopup, setisPopup] = React.useState(true);
const titleId = useId('title');
React.useEffect(() => {
showModal();
}, [isPopup]);
function ExitHandler() {
hideModal();
setisPopup(current => !current)
myprops.handler();
}
return (
<div>
<Modal
titleAriaId={titleId}
isOpen={isModalOpen}
onDismiss={ExitHandler}
isBlocking={true}
containerClassName={contentStyles.container}
>
<div className={contentStyles.header}>
<span id={titleId}>Modal Popup</span>
<IconButton
styles={iconButtonStyles}
iconProps={cancelIcon}
ariaLabel="Close popup modal"
onClick={ExitHandler}
/>
</div>
<div className={contentStyles.body}>
<p dangerouslySetInnerHTML={{__html:myprops.OurValue}}>
</p>
</div>
</Modal>
</div>
);
};
const cancelIcon: IIconProps = { iconName: 'Cancel' };
const theme = getTheme();
const contentStyles = mergeStyleSets({
container: {
display: 'flex',
flexFlow: 'column nowrap',
alignItems: 'stretch',
},
header: [
// eslint-disable-next-line deprecation/deprecation
theme.fonts.xLarge,
{
flex: '1 1 auto',
borderTop: '4px solid ${theme.palette.themePrimary}',
color: theme.palette.neutralPrimary,
display: 'flex',
alignItems: 'center',
fontWeight: FontWeights.semibold,
padding: '12px 12px 14px 24px',
},
],
body: {
flex: '4 4 auto',
padding: '0 24px 24px 24px',
overflowY: 'hidden',
selectors: {
p: { margin: '14px 0' },
'p:first-child': { marginTop: 0 },
'p:last-child': { marginBottom: 0 },
},
},
});
const stackProps: Partial<IStackProps> = {
horizontal: true,
tokens: { childrenGap: 40 },
styles: { root: { marginBottom: 20 } },
};
const iconButtonStyles: Partial<IButtonStyles> = {
root: {
color: theme.palette.neutralPrimary,
marginLeft: 'auto',
marginTop: '4px',
marginRight: '2px',
},
rootHovered: {
color: theme.palette.neutralDark,
},
};
And to secure the dangerouslySetInnerHTML, i did the following steps:-
1- Inside my Node.Js CMD >> i run this command inside my project directory:-
npm install dompurify eslint-plugin-risxss
2- Then inside my above .tsx i made the following modifications:-
I added this import import { sanitize } from 'dompurify';
An I replaced this unsafe code <p dangerouslySetInnerHTML={{__html:myprops.OurValue}}></p> with this <div dangerouslySetInnerHTML={{ __html: sanitize(myprops.OurValue) }} />
So I have the following question:-
Now my approach (of using sanitize(myprops.OurValue) will/should securely render HTML as Rich-Text inside the popup since i am using the sanitize function which is part of the dompurify eslint-plugin-risxss. but i read another approach which mentioned that to securely render HTML as Rich-Text inside the popup, we can use the html-react-parser package as follow {parse(myprops.OurValue)}. So what are the differences between using 'html-react-parser' & using 'dompurify eslint-plugin-risxss' to securely render an HTML code as Rich-Text inside the React web part's popup?
Here is my Full web part code:-
inside the MyModalPopupWebPart.ts:-
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '#microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '#microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '#microsoft/sp-webpart-base';
import * as strings from 'MyModalPopupWebPartStrings';
import MyModalPopup from './components/MyModalPopup';
import { IMyModalPopupProps } from './components/IMyModalPopupProps';
export interface IMyModalPopupWebPartProps {
description: string;
WhoWeAre: string;
OurValue:string;
}
export default class MyModalPopupWebPart extends BaseClientSideWebPart<IMyModalPopupWebPartProps> {
public render(): void {
const element: React.ReactElement<IMyModalPopupProps> = React.createElement(
MyModalPopup,
{
description: this.properties.description,
WhoWeAre: this.properties.WhoWeAre,
OurValue: this.properties.OurValue
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('WhoWeAre', {
label: "who We Are",
multiline: true
}),
PropertyPaneTextField('OurValue', {
label: "Our value"
}), PropertyPaneTextField('description', {
label: "Description",
multiline: true
}),
]
}
]
}
]
};
}
}
inside the MyModalPopup.tsx:-
import * as React from 'react';
import { IMyModalPopupProps } from './IMyModalPopupProps';
import { DefaultButton } from '#fluentui/react/lib/Button';
import { MYModal } from './MYModal';
import { MYModal2 } from './MYModal2';
interface IPopupState {
showModal: string;
}
export default class MyModalPopup extends React.Component<IMyModalPopupProps, IPopupState> {
constructor(props: IMyModalPopupProps, state: IPopupState) {
super(props);
this.state = {
showModal: ''
};
this.handler = this.handler.bind(this);
this.Buttonclick = this.Buttonclick.bind(this);
}
handler() {
this.setState({
showModal: ''
})
}
private Buttonclick(e, whichModal) {
e.preventDefault();
this.setState({ showModal: whichModal });
}
public render(): React.ReactElement<IMyModalPopupProps> {
const { showModal } = this.state;
return (
<div>
<DefaultButton onClick={(e) => this.Buttonclick(e, 'our-value')} text="Our Value" />
{ showModal === 'our-value' && <MYModal2 OurValue={this.props.OurValue} myprops={this.state} handler={this.handler} />}
<DefaultButton onClick={(e) => this.Buttonclick(e, 'who-we-are')} text="Who We Are" />
{ showModal === 'who-we-are' && <MYModal WhoWeAre={this.props.WhoWeAre} myprops={this.state} handler={this.handler} />}
</div>
);
}
}
Actually, html-react-parser returns ReactJs object, and its return type is like React.createElement or like type of called JSX.
Using DOMPurify.sanitize will return safe pure HTML elements which those are different to the object that html-react-parser returns. the risxss ESLint plugin will force you to use sanitizing with any kind of sanitize function or library, that I left an answer to your other question to how to Sanitize your string HTML.
Eventually, using sanitizing is better because is the html-react-parser will convert your string HTML to ReactJs object with some tiny changes that would be dangerous because it is possible to have some script of string HTML in the project and it maybe will be harmful it just remove the onclick or onload, etc, from HTML tags but sanitizing will remove all possible harmful tags. also sanitizing will receive configuration, which means you can have your own options for sanitizing.

How to change a button color with a JS variable

What i try to achieve is, to set a button color based on the current SDG ( understand it as a chapter). So i want to set the chapter name using a variable sdg and then i want to apply the right color from a css file to the buttons in the constructor. I already used a similar approach in the header where the ClassName contains a variable sdg so the right css is picked, but it seems it only works after i return().
If you need a better explenation or have a better approach please write it too.
Edit: please take it easy on me , im only 16 and dont know much ;)
// eslint-disable-next-line eslint-comments/disable-enable-pair
/* eslint-disable unicorn/filename-case */
import * as React from "react";
import Modal, { ICustomModalStyle } from "#bdenzer/react-modal";
import Logo from "../../../SDGLogos/Goal-06.png";
interface States {
button1color: string;
button2color: string;
shouldShowModal: boolean;
onlyCloseWithButton: boolean;
}
const sdg = "SDG06";
const buttonsdg = getComputedStyle(app.colour_SDG01);
// eslint-disable-next-line react/prefer-stateless-function
export class Quiz extends React.Component<unknown, States> {
constructor(props: unknown) {
super(props);
this.state = {
button1color: "rgb(204,204,255)",
button2color: "blue",
shouldShowModal: false,
onlyCloseWithButton: true,
};
this.closeModal = this.closeModal.bind(this);
this.openModal = this.openModal.bind(this);
}
handleClick(): void {
this.setState(({ button1color }) => ({
button1color: "green",
button2color: "red",
}));
}
private closeModal(): void {
this.setState({ shouldShowModal: false });
}
private openModal(): void {
this.setState({ shouldShowModal: true });
}
render(): JSX.Element {
const modalStyle: ICustomModalStyle = {
animationTime: 400,
closeButtonText: {
color: "white",
},
hoveredButtonText: {
fontWeight: "bold",
},
modalHeader: {
backgroundColor: "green",
},
modalTitle: {
color: "white",
},
};
return (
<div>
<div className={`colour_${sdg}`}>
<div className="header">
Hochwertige Bildung <img className="sdglogo" alt="logo" src={Logo} />
</div>
</div>
<p className="quizQuestion">Does a passenger car or a plane produce more greenhouse gases?</p>
<div>
<button
className="answerButtonleft"
style={{ backgroundColor: this.state.button1color }}
type="button"
onClick={() => {
this.handleClick();
setTimeout(() => {
this.openModal();
}, 1000);
}}
>
The passenger car
</button>
<button
className="answerButtonright"
style={{ backgroundColor: this.state.button2color }}
type="button"
onClick={() => {
this.handleClick();
setTimeout(() => {
this.openModal();
}, 1000);
}}
>
The plane
</button>
</div>
<div>
<Modal
closeModal={this.closeModal}
customStyle={modalStyle}
shouldShowModal={this.state.shouldShowModal}
title="React Modal in TypeScript"
onlyCloseWithButton={this.state.onlyCloseWithButton === true}
>
The plane does. Studies show that a plane produces about 230 grams per Person per kilometer
(g/Pkm) while a passenger car only frees about 147 g/Pkm.
</Modal>
</div>
</div>
);
}
}
:root { --SDG01color: #E5243B; }
:root { --SDG02color: #DDA63A;}
:root { --SDG03color: #4C9F38;}
:root { --SDG04color: #C5192D;}
:root { --SDG05color: #FF3A21;}
:root { --SDG06color: #26BDE2;}
:root { --SDG07color: #FCC30B;}
:root { --SDG08color: #A21942;}
:root { --SDG09color: #FD6925;}
:root { --SDG10color: #DD1367;}
:root { --SDG11color: #FD9D24;}
:root { --SDG12color: #BF8B2E;}
:root { --SDG13color: #3F7E44;}
:root { --SDG14color: #0A97D9;}
:root { --SDG15color: #56C02B;}
:root { --SDG16color: #00689D;}
:root { --SDG17color: #19486A ;}
.colour_SDG01{
background-color: var(--SDG01color);
}
.colour_SDG02{
background-color: var(--SDG02color);
}
.colour_SDG03 {
background-color: var(--SDG03color);
}
.colour_SDG04 {
background-color: var(--SDG04color);
}
.colour_SDG05 {
background-color: var(--SDG05color);
}
.colour_SDG06 {
background-color: var(--SDG06color);
}
.colour_SDG07 {
background-color: var(--SDG07color);
}
.colour_SDG08 {
background-color: var(--SDG08color);
}
.colour_SDG09 {
background-color: var(--SDG09color);
}
.colour_SDG10 {
background-color: var(--SDG10color);
}
.colour_SDG11 {
background-color: var(--SDG11color);
}
.colour_SDG12 {
background-color: var(--SDG12color);
}
.colour_SDG13 {
background-color: var(--SDG13color);
}
.colour_SDG14{
background-color: var(--SDG14color);
}
.colour_SDG15 {
background-color: var(--SDG15color);
}
.colour_SDG16 {
background-color: var(--SDG16color);
}
.colour_SDG17 {
background-color: var(--SDG17color);
}
Just add the className={`colour_${sdg}`} attribute to your buttons, like you did in your header! e.g. className={`answerButtonleft colour_${sdg}`}
You can remove the style={{ backgroundColor: ... }} statements from the elements, the computed style part, and the button colours from your state.
I assume the answerButtonleft and similar classes are in another CSS file, or you just haven't pasted, or haven't yet implemented them.

React How to use different states with click event

In short:
I'm implementing Simon-Says game app in React Native. (user sees a sequence of flashing buttons, needs to press the buttons in the correct order).
I want to know how to use 2 different states in TouchableOpacity, one of them as a condition to press the button, one for changing the style of the button, and also being notified for this specific press.
So,
I'm having a problem to implement the playerTurn(),
because I'm not sure how to pass the canPress state to the TouchableOpacity button,
considering I'm passing style state that changes in compTurn()
(function that shows a sequence of flashing buttons - then computer turn's over)
In the player turn, things I need to consider:
after the state canPress changes, the user will be allowed to press on the buttons
user presses one of the 4 buttons
the method playerTurn() will be notified which button did the player pressed. (I'm asking how can I get that notification from the button to the method?)
after that, I can push it's choice to the playerSeq array (if pressed green - pushes 1, etc) and call function that changes the style state (greenFlash for example)
code in short :
export default class App extends Component{
constructor (props){
super(props);
this.seq=[1,2,3,1,4] //will be random, this is just for testing
this.playerSeq=[]
...
this.state = {
canPress: false,
greenB: {
backgroundColor: 'darkgreen'
}, ...
playerTurn(){
this.setState({canPress: true})
// if the user pressed on the green button, then I push 1 to the playerSequence
// More functionality will be here
}
render(){
return (..
<TouchableOpacity style={[styles.greenB, this.state.greenB]}></TouchableOpacity>
//I ALSO WANT TO PASS THE STATE CANPRESS + NOTIFY PLAYERTURN() THAT THE USER PRESSED ON THIS BUTTON
Full code: (not the full game, note that I'm learning react just in the past few days)
export default class App extends Component{
constructor (props){
super(props);
this.flash=0
this.round=1
this.seq=[1,2,3,1,4] //will be random, this is just for testing
this.playerSeq=[]
this.win=false
this.ok=true
this.score=0
this.state = {
canPress: false,
greenB: {
backgroundColor: 'darkgreen'
},
yellowB: {
backgroundColor: 'orange'
},
blueB: {
backgroundColor: 'blue'
},
redB: {
backgroundColor: 'red'
}
}
this.play=this.play.bind(this)
this.greenFlash=this.greenFlash.bind(this)
this.blueFlash=this.blueFlash.bind(this)
this.redFlash=this.redFlash.bind(this)
this.playerTurn=this.playerTurn.bind(this)
}
play(){
this.flash=0
this.round=1 //round will increase, this is just for test
this.win=false
this.ok=true
this.score=0
this.compTurn();
this.playerTurn();
}
playerTurn(){
this.setState({canPress: true})
}
compTurn() {
let intervalId = setInterval(()=> {
if (this.flash==this.round) {
clearInterval(intervalId);
}
else {
if (this.seq[this.flash]==1){
this.greenFlash();
}
if (this.seq[this.flash]==2){
this.yellowFlash();
}
if (this.seq[this.flash]==3){
this.blueFlash();
}
if (this.seq[this.flash]==4){
this.redFlash();
}
this.flash++;
}
}
, 1500);
}
greenFlash(){
setTimeout(() => {
this.setState( {
greenB:{
...this.state.style1, backgroundColor: 'lightgreen'
}
})
}, 200);
setTimeout(() => {
this.setState( {
greenB:{
...this.state.style1, backgroundColor: 'darkgreen'
}
})
}, 1000);
}
yellowFlash(){
setTimeout(() => {
this.setState( {
yellowB:{
...this.state.style1, backgroundColor: 'yellow'
}
})
}, 200);
setTimeout(() => {
this.setState( {
yellowB:{
...this.state.style1, backgroundColor: 'orange'
}
})
}, 1000);
}
blueFlash(){
setTimeout(() => {
this.setState( {
blueB:{
...this.state.style1, backgroundColor: 'lightblue'
}
})
}, 200);
setTimeout(() => {
this.setState( {
blueB:{
...this.state.style1, backgroundColor: 'blue'
}
})
}, 1000);
}
redFlash(){
setTimeout(() => {
this.setState( {
redB:{
...this.state.style1, backgroundColor: 'pink'
}
})
}, 200);
setTimeout(() => {
this.setState( {
redB:{
...this.state.style1, backgroundColor: 'red'
}
})
}, 1000);
}
render(){
return (
<View>
<TouchableOpacity style={styles.playB}
onPress={this.play}>
<Text style={{
color:'white',
height: 30,
width:60,
}}>START</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.greenB, this.state.greenB]}></TouchableOpacity>
<TouchableOpacity style={[styles.yellowB, this.state.yellowB]}></TouchableOpacity>
<TouchableOpacity style={[styles.blueB, this.state.blueB]}></TouchableOpacity>
<TouchableOpacity style={[styles.redB, this.state.redB]}></TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
greenB:{
padding: 5,
height: 80,
width: 80,
borderRadius:160,
},
yellowB:{
padding: 5,
height: 80,
width: 80,
borderRadius:160,
},
blueB:{
padding: 5,
height: 80,
width: 80,
borderRadius:160,
},
redB:{
padding: 5,
height: 80,
width: 80,
borderRadius:160,
},
playB:{
alignSelf: 'center',
backgroundColor: 'blue',
}
});
Looks like you want to enable clicking on the buttons if state.canPress = true right? Then upon clicking, you wish to notify by calling playerTurn()?
You can do something like this for e.g your green button.
<TouchableOpacity style={[styles.greenB, this.state.greenB]} onPress={this.state.canPress && () => {
this.playerTurn(1);
// Whatever you want to do on green button pressed by player in here.
}>
</TouchableOpacity>
this.setState also has a callback function as its second parameter, which may be more useful in your flash method.

How to fix translate which contains state, which changed by 'interval' (React)

I have a procedure for a timer for animation. I want to make an animation of logos like https://stripe.com/us/customers. But I have an endless loading of the page, so it doesn't work.
I tried to use a procedure in different parts of the code and tried to change interval for better optimization (I think my PC can't work with 1 ms interval), but it didn't help me.
It all from one file.
State:
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
submitError: false,
width: 0,
height: 0,
timer: 0
};
Procedure:
TimeForLogos() {
const time = setInterval(() => {
const passedTime = this.state.timer + 0.1;
if (passedTime === 20) {
clearInterval(time);
}
this.setState({
timer: passedTime,
});
}, 100);
}
I try to use it in render (I need that procedure begins when the site is opened) and try to make a button (I thought it help me to solve the problem of endless loading). So part of code from render for now:
<div className={s.logos}>
<span onClick={this.TimeForLogos()}>go</span>
{LogoData.map(logo => (
<div
className={s.logo}
style={{
right: `${logo.positionX}px`,
top: `${logo.positionY}px`,
width: logo.width * 1.1,
padding: `${(logo.width - logo.height) / 2} 0`,
transform: `translate(${this.state.timer * 10}px,0) scale(1)`,
}}
>
<img
src={logo.img}
alt=""
style={{
width: logo.width,
height: logo.height,
}}
/>
</div>
))}
</div>
So, a question. How can I update my code that it works? And I need to make so that procedure works when the site is opening (animation must play when the site is opened). How I can do it?
You can create a separate component and handle the transition of each component in the timeout function.
class Home extends Component {
constructor(props) {
super(props);
this.logoData = [{
width: 100,
height: 100,
text: "text1"
},
{
width: 100,
height: 100,
text: "text2"
},
{ width: 100,
height: 100,
text: "text3"
}];
}
render() {
return (
<div className="mainContainer">
{this.logoData.map(item => <MovingDiv {...item}/>)}
</div>
);
}
}
Creating one more react-component say MovingDiv.
class MovingDiv extends Component {
constructor(props) {
super(props);
this.state = {
translateX: 0,
translateY: 0,
scale: 0
}
}
componentDidMount() {
const intervalLimit = setInterval(() => {
let { translateX, translateY} = this.state;
// logic of setting translateX goes here
if(--translateX < -300) { // -300 is just for example
translateX = 0;
}
this.setState({
translateX
})
}, 200)
}
/* will move the divs towards right every 200ms*/
render() {
return(<div style={{ width: this.props.width, height: this.props.height, transform: `translate(${this.state.translateX}px, 0px)`}}>{this.props.text}</div>);
}
}
Hope this helps!
I updated something in code of previous commentator. I make everything in one class (Home). I make json file for logos and info contains in this file. So it's my code.
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
translateX: 0,
};}
render() {
setInterval(() => {
let { translateX } = this.state;
translateX -= 2;
if (translateX < -1800) {
translateX = 0;
}
this.setState({
translateX,
});
}, 1000);
<div className={s.logos}>
{LogoData.map(logo => (
<div
className={s.logo}
style={{
left: `${logo.positionX}px`,
top: `${logo.positionY}px`,
width: logo.width * 1.1,
padding: `${(logo.width - logo.height) / 2} 0`,
transform: `translate(${this.state.translateX}px,0) scale(1)`,
}}
>
<img
src={logo.img}
alt=""
style={{
width: logo.width,
height: logo.height,
}}
/>
</div>
))}
</div>

Categories