In that image i can explain what is my question
import './App.css';
import { useState } from 'react'
function App() {
const [head,setHead] = useState([])
const [tail,setTail] = useState([])
const main = [];
main.push(head,tail)
console.log(main);
const handleHead = () =>{
const HeadButton = 'H'
setHead([...head,HeadButton])
}
const handleTail = () =>{
const TailButton = 'T'
setTail([...tail,TailButton])
}
return (
<div className="App">`your text`
<button onClick={(e)=>handleHead(e)} >Head</button>
<button onClick={(e)=>handleTail(e)}>Tail</button>
<h1>{head.join(',')}</h1>
<h1>{tail.join(',')}</h1>
</div>
);
}
export default App;
i can 2 array inside of main array than how can create a third array inside of main array in react js
try this
// Get a hook function
const {useState} = React;
const Example = ({title}) => {
const [FinalList, setFinalList] = useState([]);
const [ConsecutiveHead, setConsecutiveHead] = useState(false);
const [ConsecutiveTail, setConsecutiveTail] = useState(false);
const handleHead = () =>{
if(ConsecutiveHead) {
const list = [...FinalList];
list[list.length -1].push("head");
setFinalList(list);
} else {
setFinalList(prev => [...prev, ["head"]]);
}
setConsecutiveHead(true);
setConsecutiveTail(false);
}
const handleTail = () =>{
if(ConsecutiveTail) {
const list = [...FinalList];
list[list.length -1].push("tail");
setFinalList(list);
} else {
setFinalList(prev => [...prev, ["tail"]]);
}
setConsecutiveHead(false);
setConsecutiveTail(true);
}
console.log(FinalList)
return (
<div className="App">
<button onClick={(e)=>handleHead(e)} >Head</button>
<button onClick={(e)=>handleTail(e)}>Tail</button>
</div>
);
};
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render(
<Example title="Example using Hooks:" />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
Related
I Can't render my events. Its showing this error -
"Cannot update a component (App) while rendering a different component (EventList). To locate the bad setState() call inside EventList, follow the stack trace as described in https://reactjs.org/link/setstate-in-render"
Here is EventList Component code -
import { useEffect, useState } from "react";
import EventList from "../../event-list";
import EventForm from "../event-form";
const EventAction = ({
getEventsByClockID,
addEvent,
updateEvent,
clockID,
deleteEvent,
deleteEventsByClockID,
}) => {
const [isCreate, setIsCreate] = useState(false);
const [isToggle, setIsToggle] = useState(false);
const [eventState, setEventState] = useState(null)
const handleCreate = () => {
setIsCreate(!isCreate);
}
useEffect(() => {
setEventState(getEventsByClockID(clockID, true));
}, [isToggle])
const handleToggle = () => {
setIsToggle(!isToggle);
}
return (
<div>
<div>
<button onClick={handleCreate}>Create Event</button>
<button onClick={handleToggle}>Toggle Events</button>
</div>
{isCreate && (
<>
<h3>Create Event</h3>
<EventForm
clockID={clockID}
handleEvent={addEvent}
/>
</>
)}
{isToggle && (
<>
<h3>Events of this clock</h3>
<EventList
clockID={clockID}
eventState={eventState}
deleteEvent={deleteEvent}
updateEvent={updateEvent}
deleteEventsByClockID={deleteEventsByClockID}
/>
</>
)}
</div>
)
}
export default EventAction;
Here is my App Component Code -
import ClockList from "./components/clock-list";
import LocalClock from "./components/local-clock";
import useApp from "./hooks/useApp";
import { localClockInitState } from "./initialStates/clockInitState";
const App = () => {
const {
localClock,
clocks,
updateLocalClock,
createClock,
updateClock,
deleteClock,
getEventsByClockID,
addEvent,
deleteEvent,
updateEvent,
deleteEventsByClockID,
} = useApp(localClockInitState);
return (
<div>
<LocalClock
clock={localClock}
updateClock={updateLocalClock}
createClock={createClock}
/>
<ClockList
clocks={clocks}
localClock={localClock.date}
updateClock={updateClock}
deleteClock={deleteClock}
getEventsByClockID={getEventsByClockID}
addEvent={addEvent}
deleteEvent={deleteEvent}
updateEvent={updateEvent}
deleteEventsByClockID={deleteEventsByClockID}
/>
</div>
)
}
export default App;
and Here is my useApp hook -
import { useState } from "react";
import deepClone from "../utils/deepClone";
import generateID from "../utils/generateId";
import useEvents from "./useEvents";
const getID = generateID('clock');
const useApp = (initValue) => {
const [localClock, setLocalClock] = useState(deepClone(initValue));
const [clocks, setClocks] = useState([]);
const {
// events,
// getEvents,
getEventsByClockID,
addEvent,
deleteEvent,
deleteEventsByClockID,
updateEvent,
} = useEvents();
const updateLocalClock = (data) => {
setLocalClock({
...localClock,
...data,
})
}
const createClock = (clock) => {
clock.id = getID.next().value;
setClocks((prev) => ([
...prev, clock
]))
}
const updateClock = (updatedClock) => {
setClocks(clocks.map(clock => {
if(clock.id === updatedClock.id) return updatedClock;
return clock;
}));
}
const deleteClock = (id) => {
setClocks(clocks.filter(clock => clock.id !== id));
}
return {
localClock,
clocks,
updateLocalClock,
createClock,
updateClock,
deleteClock,
getEventsByClockID,
addEvent,
deleteEvent,
updateEvent,
deleteEventsByClockID,
}
}
export default useApp;
I want to show all events incorporated with each individual clock.
I am trying to update the value of a counter when I hold a button in my react app. However I am encountering a problem where the couunter isn't being updated unless I spam click the button. I expect to be able to hold the button to have the counter to increment as the amount of time I hold the button increase.
Here is a example of what I am truing to do:
import { useRef, useState } from "react";
function App() {
const [rpm, setRpm] = useState("");
const [rpmTxt, setRpmText] = useState("");
const [interval, setIntervalID] = useState(NaN);
const [isHoldingButton, setHoldingButton] = useState(false);
useRef(() => {
setRpmText("RPM: " + timeHeld);
}, [rpm]);
function onButtonHold() {
if (isHoldingButton)
return;
setHoldingButton(true)
setIntervalID(setInterval(() => {
setRpm(rpm + 50);
}, 50))
}
function onButtonRelease() {
setHoldingButton(false)
clearInterval(interval)
}
return (
<div id="app">
<button onPointerDown={onButtonHold} onPointerUp={onButtonRelease}>Button hold</button>
<p>{timeHeldText}</p>
</div>
)
}
ReactDOM.(<App />, document.getElementByID("root"));
ReactDOM.render(<App />, document.getElementById("root"))
I tried to use a useRef hook to keep the timout id however it didn't worked out as the useRef property is immutable therefore can't be changed.
function App() {
const [rpm, setRpm] = useState("");
const [rpmTxt, setRpmText] = useState("");
const intervalIdRef = useRef(null)
const [isHoldingButton, setHoldingButton] = useState(false);
useRef(() => {
setRpmText("RPM: " + timeHeld);
}, [rpm]);
function onButtonHold() {
if (isHoldingButton)
return;
setHoldingButton(true)
intervalIdRef.current = setInterval(() => {
setRpm(rpm + 50);
}, 50)
}
function onButtonRelease() {
setHoldingButton(false)
clearInterval(intervalIdRef.current)
}
return (
<div id="app">
<button onPointerDown={onButtonHold} onPointerUp={onButtonRelease}>Button hold</button>
<p>{timeHeldText}</p>
</div>
)
}
ReactDOM.(<App />, document.getElementByID("root"));
ReactDOM.render(<App />, document.getElementById("root"))
try this:
function App() {
const [rpm, setRpm] = useState(0);
const [interval, setIntervalID] = useState(NaN);
const [isHoldingButton, setHoldingButton] = useState(false);
const getRpmText = () => "RPM: " + rpm;
function onButtonHold() {
if (isHoldingButton)
return;
setHoldingButton(true)
let value = 0;
setIntervalID(setInterval(() => {
setRpm(value += 50);
}, 50))
}
function onButtonRelease() {
setHoldingButton(false)
clearInterval(interval)
setRpm(0);
}
return (
<div id="app">
<button onPointerDown={onButtonHold} onPointerUp={onButtonRelease}>Button hold</button>
<p>{getRpmText()}</p>
</div>
)
}
import React,{useRef} from "react"
const FuncComp = () => {
const videoItems = useRef();
const addVideo (stream){
videoItems.current.append(<video src = {stream}> </video>);
};
return (
<div ref = {videoItems}>
</div>
)
}
But addVideo function is not working as i can not append video tag to the div. is there another way to achive this?
you can write your code like this:
import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";
const MyComponent = () => {
const [videos, setVideos] = useState([]);
const addVideo = (id, stream) => {
const videosTemp = [...videos];
videosTemp.push({ id, stream });
setVideos(videosTemp);
};
const onAddVideoClick = () => {
const id = uuidv4();
const stream = "https://www.youtube.com/watch?v=haMOUb3KVSo";
addVideo(id, stream);
};
return (
<div>
<button onClick={onAddVideoClick}>Add Video</button>
{videos.map((video) => {
<video key={video.id} src={video.src} />;
})}
</div>
);
};
I am trying to create dynamically element on button click and append it to one of the classes by using ref.
I can use document.createElement but from what I read do not use it in react
For example I want to add an element of <p> to div with class name of classes.elements by clicking the button
import React, { useRef } from 'react'
import classes from './AddElement.scss'
const AddElement = (props) => {
const elementRef = useRef(null)
const addElement = () => {
<p>This is paragraph</p>
}
return (
<div>
<button onClick={() => addElement()}>Click here</button>
<div ref={elementRef} className={classes.elements}>
</div>
</div>
)
}
export default AddElement;
You could try using the useState hook like this :
import React, { useState } from 'react';
import classes from './AddElement.scss';
const AddElement = () => {
const [dynamicElems, setDynamicElems] = useState([]);
const addElement = () => {
// Creates the dynamic paragraph
const newDynamicElem = <p className={classes.elements}>This is paragraph</p>;
// adds it to the state
setDynamicElems(() => [...dynamicElems, newDynamicElem]);
};
return (
<div>
<button onClick={() => addElement()}>Click here</button>
<div className={classes.elements}>{dynamicElems}</div>
</div>
);
};
export default AddElement;
const AddElement = (props) => {
const [dynamicCompList, setDynamicCompList] = useState([]);
const addElement = () => {
const dynamicEl = React.createElement("p", {}, "This is paragraph");
setDynamicCompList(dynamicCompList.concat(dynamicEl));
}
return (
<div>
<button onClick={() => addElement()}>Click here</button>
<div className={classes.elements}>
{dynamicCompList}
</div>
</div>
)
}
export default AddElement;
Try this:
const addElement = () => {
const para = document.createElement("p");
para.innerHTML = 'Hello';
elementRef.current.appendChild(para);
};
<div ref={elementRef}></div>
<button onClick={addElement}>Click me</button>
Approach 1
import React, { useRef, useState } from "react";
import classes from "./App.module.scss";
export default function App() {
const componetRef = useRef(null);
const [contentValue, setContentValue] = useState([]);
const addElement = () => {
const content = "this is para";
const type = componetRef.current.dataset.type || "p";
const classNames = componetRef.current.className;
const elemnt = React.createElement(type, { key: Date.now() }, content);
setContentValue([
...contentValue, // If you dont want to make it multiple times. just remove it
elemnt
]);
};
return (
<div className="App">
<button onClick={addElement}>Click here</button>
<div data-type="h1" ref={componetRef} className={classes.tag1}>
{contentValue}
</div>
</div>
);
}
Approach 2
import React, { useState } from "react";
import classes from "./App.module.scss";
const NewComponent = ({ classNames, content }) => {
return (
<div className={classNames} dangerouslySetInnerHTML={{ __html: content }} />
);
};
export default function App() {
// const classRef = useRef(null);
const [multiple, setMultiple] = useState([]);
const addElement = (e) => {
const classNames = e.target.dataset.class;
const content = e.target.dataset.content;
setMultiple([
...multiple, // If you dont want to make it multiple times. just remove it
<NewComponent
key={Date.now()}
classNames={classNames}
content={content}
/>
]);
};
return (
<div className="App">
<button
onClick={addElement}
data-class={classes.tag1}
data-content={"<p>asdasd</p>"}
>
Click here
</button>
{multiple}
</div>
);
}
Let me know if you have more question.
Here is sandbox
When running my express react app build locally the map function works flawlessly, however whenever I switch to production. I get the error that map is not a function.
Error comes up pointing towards 'let returnlist' line. I have included the index.js and where the error occurs.
import React, { useState, useEffect } from 'react'
import ReactDOM from 'react-dom'
import AddNewPerson from './component/addNew'
import Filter from './component/filter'
import Persons from './component/persons'
import axios from 'axios'
const App = () => {
const [persons, setPersons] = useState([])
const [tempPersonList, setTempPersonList] = useState([])
const [ newName, setNewName ] = useState('')
const [ newNumber, setNewNumber] = useState('')
let searchInput = false;
useEffect(() => {
axios
.get('http://localhost:3001/init')
.then(response => {
console.log(response.data)
setPersons(response.data)
setTempPersonList(response.data)
})
}, [])
return (
<div>
<Filter persons = {persons} setPersons= {setPersons} tempPersonList = {tempPersonList}
searchInput = {searchInput}/>
<AddNewPerson persons = {persons} setPersons= {setPersons} newName = {newName}
setNewName = {setNewName} setNewNumber = {setNewNumber} newNumber = {newNumber} />
<Persons persons = {persons} setPersons = {setPersons} tempPersonList = {tempPersonList} searchInput = {searchInput} />
...
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
The error occurs in the code below on 'let returnList'.
const Persons = (props) => {
const persons = props.persons
const setPersons = props.setPersons
const tempPersonList = props.tempPersonList
let searchInput = props.searchInput
let returnList = persons.map((person) => <li className='contact' key = {person.number}>{person.name} : {person.number} <button onClick={
() =>{ Axios.delete(`${url}/${person.id}`)
.then((response) =>{
setPersons(persons.filter(personCheck => personCheck.id !== person.id ))
})}}>Remove</button></li>)
let returnSearchList = tempPersonList.map((person) => <li key = {person.number}>{person.name} : {person.number} <button onClick={
() =>{ Axios.delete(`${url}/${person.id}`)
.then((response) =>{
setPersons(persons.filter(personCheck => personCheck.id !== person.id ))
})}}>Remove</button></li>)
return(
<div>
<h2>
Numbers
</h2>
{searchInput ? returnSearchList : returnList}
</div>
)
}
export default Persons
Many Thanks
Your response data doesn't return an array, it's probably an object. Check in the network tab of your browser what your AJAX call returns.
Or just open this in your browser: http://localhost:3001/init
The data field of whatever is shown has to be an array.