Problem while passing useState variable from one JSX file to another - javascript

(CreateColumn.jsx)
import React, { useState, useEffect } from "react";
import Axios from "axios";
import "./styles.css";
function CreateColumn() {
let [val1, setVal1] = useState("0");
let [val2, setVal2] = useState("0");
let [secName, setSecName] = useState("");
let [goAttendance, setGoAttendance] = useState(0);
function valueChanged(event) {
const checkChecked = event.target.id;
// console.log(checkChecked);
if (checkChecked === "section1") {
setVal1("1");
setVal2("0");
setSecName("Section 1");
} else if (checkChecked === "section2") {
setVal2("1");
setVal1("0");
setSecName("Section 2");
} else {
setVal1("0");
setVal2("0");
setSecName("");
}
}
useEffect(() => {
Axios.get("http://localhost:9000/createColumn").then((response) => {
setSecName(response.data);
});
}, []);
function sendColumn(event) {
setGoAttendance(1);
Axios.post("http://localhost:9000/createColumn", { secName, goAttendance });
}
return (
<div>
<form className="form-body">
<div className="form-check check-line center-col">
<input
className="form-check-input"
type="checkbox"
id="section1"
name="section"
value={val1}
checked={val1 === "1"}
onChange={valueChanged}
/>
</div>
<div className="form-check check-line center-col">
<input
className="form-check-input"
type="checkbox"
id="section2"
name="section"
value={val2}
checked={val2 === "1"}
onChange={valueChanged}
/>
</div>
<div className="submit-btn d-grid gap-2 d-md-flex justify-content-md-center">
<button
type="submit"
className="btn btn-lg btn-primary"
onClick={sendColumn}
>
Create
</button>
</div>
</form>
</div>
);
}
export default CreateColumn;
(Attendance.jsx)
import React, { useState, useEffect } from "react";
import Axios from "axios";
import TableTitle from "./TableTitle";
import Pagination from "./Pagination";
import "./styles.css";
function Attendance() {
const [attedanceList, setAttedanceList] = useState([]);
useEffect(() => {
Axios.get("http://localhost:9000/attendance/" + ****WANT TO USE secName FROM CreateColumn.jsx HERE****).then(
(response) => {
setAttedanceList(response.data.data.values);
}
);
}, []);
function sendAllValues(event) {
Axios.post("http://localhost:9000/attendance", { attedanceList });
}
return (
<form className="form-body">
<TableTitle />
<Pagination data={attedanceList} />
<div className="submit-btn d-grid gap-2 d-md-flex justify-content-md-center">
<button
type="submit"
className="btn btn-lg btn-primary"
onClick={sendAllValues}
>
Submit
</button>
</div>
</form>
);
}
export default Attendance;
(App.jsx)
import React, { useState } from "react";
import Attendance from "./Attendance";
import CreateColumn from "./CreateColumn";
function App() {
return (
<div>
<CreateColumn />
**WANT TO USE goAttendance FROM CreateColumn.jsx HERE** && <Attendance />
</div>
);
}
export default App;
I wanna use useState variables (secName and goAttendance) from Column.jsx in Attendance.jsx and App.jsx (where I have marked as WANT TO USE...). How is it possible?
More precisely, I wanna use secName from Column.jsx into Attendance.jsx.
Also, I wanna use goAttendance from Column.jsx into App.jsx
I tried so many things for hours but sometimes it breaks my code or simply have to change a lot which makes the code more messy and buggy.

As I can see CreateColumn and Attendence are the child components of App. You want to create a state and use it in app where as you want to set it in its child component. What I will suggest is to create the state and setState function on app level and then pass the state and setState function as props in the child component. I will suggest you to see this to know more about props.
in app.jsx
let [val1, setVal1] = useState("0");
let [val2, setVal2] = useState("0");
let [secName, setSecName] = useState("");
let [goAttendance, setGoAttendance] = useState(0);
const [attedanceList, setAttedanceList] = useState([]);
// while calling the components
return(
<>
<CreateColumn val1={val1}, val2={val2}, secName={secName}, ....../>
<Attendance val1={val1}, val2={val2}, secName={secName}, ....../>
</>
)
in CreateColumn and Attendence while declaring the components write
function Attendance({val1, val2, secName, setVal1, ...})
and then use the states and setStates in app.jsx

Related

I have two React components fetching from a Flask App. One works but one doesn't

import './Checklist.css'
import { useEffect, useState } from 'react'
import axios from "axios";
const fetchData = (hook) => {
return axios.get("http://localhost:5000/shopping")
.then((response) => hook(response.data.shoppingList));
}
function Checklist() {
const [shoppingList, setShoppingList] = useState();
useEffect(() => {
fetchData(setShoppingList)
}, []);
return (
<div className='checklist-div'>
<header>Shopping List</header>
<div className='shopping-div'>
{shoppingList.map((entry, index) => {
if (index % 3) {
return (
<div className="form-check form-switch" key={index}>
<input className="form-check-input" disabled id={`${entry}-input`} type="checkbox" />
<label className="form-check-label" >{entry}</label>
</div>
)
}
return (
<div className="form-check form-switch" key={index}>
<input className="form-check-input" id={`${entry}-input`} type="checkbox" />
<label className="form-check-label" >{entry}</label>
</div>
)
}
)};
</div>
</div>
);
}
export default Checklist;
Checklist is grabbing a json object containing an array from the server but gives a 'Can't perform a React state update on a component that hasn't mounted yet'. I've checked and the route used does give the array when accessed directly but my handling of the response in the code is causing problems
import logo from './logo.svg';
import { useState, useEffect } from 'react';
import './ReactLogo.css'
import axios from "axios";
const fetchData = (hook) => {
return axios.get("http://localhost:5000/")
.then((response) => hook(response.data.greeting));
}
function ReactLogo() {
const [heartbeat, setHeartbeat] = useState();
fetchData(setHeartbeat);
return (
<div className="react-logo-div">
<img src={logo} className="react-logo" alt="logo" />
<p>
Edit <code>src/ReactLogo.js</code> and save to reload.
</p>
<a
className="react-logo-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn Unit Tests
</a>
<p>
{heartbeat}
</p>
</div>
);
}
export default ReactLogo;
I use the same implementation for reactLogo.js and it works fine just grabbing a JSON string object

Importing a filter variable from one Component to Another Component in REACT

So I have these 2 components:
First One MAIN PAGE
`
import {useEffect, useState} from 'react';
import Navbar from "./navbar";
import Modal from "./Modal";
import '../styles/home.css'
import FavoriteCrypto from "./favoriteCrypto";
export default function MainPage() {
const[data, setData] = useState([])
const[input, setInput] = useState("");
const [openModal, setOpenModal] = useState(false)
const [modalArr, setModalArr] = useState([])
const[favorites, setFavorites] = useState([])
const url = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false"
useEffect(()=>{
fetch(url)
.then((res)=>{
return res.json()
})
.then((data)=>{
setData(data)
})
},[])
let searchBar = data.filter((e)=>{
return e.id.toLowerCase().includes(input.toLowerCase())
})
// add to favorite
function addToFav(id){
if(!favorites.includes(id)){
setFavorites(favorites.concat(id))
}
}
function openModalFunc(id) {
setOpenModal(true);
if(!modalArr.includes(id)) {
setModalArr(modalArr.concat(id))
}
}
function closeModalFunc(id) {
setOpenModal(false);
setModalArr([]);
}
let modalRender = data.filter(data => modalArr.includes(data.id));
let favoriteRender = data.filter(data => favorites.includes(data.id))
console.log(favoriteRender)
return(
<div>
<Navbar input={input} setInput={setInput}/>
<div className='general-info'>
<h4>Coin</h4>
<h4 className='p'>Price</h4>
<h4 className='c'>Change</h4>
<h4 className='mc'>Market Cap</h4>
<h4 className='s'>Supply</h4>
</div>
<Modal addFavorite = {addToFav} modalArr={modalRender} close = {closeModalFunc} open = {openModal}/>
{searchBar.map((e)=>(
<div
onClick={()=>{
openModalFunc(e.id);
}}
className='all_coins_wrapper'>
<div className='coins-wrapper'>
<div className='coins-label'>
<img src={e.image} alt=""/>
<div className='general_info'>
<div>{e.name}</div>
<div>{e.symbol.toUpperCase()}</div>
</div>
</div>
<p className='price-main'>${e.current_price}</p>
</div>
<div className='left-part'>
<p className='change'>{e.price_change_percentage_24h}</p>
<div className='marcap'>{e.market_cap}</div>
<div className='circ'>{e.circulating_supply}</div>
</div>
</div>
)
)}
</div>
)
}
SECOND ONE :
`
import React from "react";
import Navbar from "./navbar";
import MainPage from "./home";
export default function FavoriteCrypto({favorite}){
return(
<div>
</div>
)
}
I want to import these variable '
let favoriteRender = data.filter(data => favorites.includes(data.id))
from the first component to the second one in order to display on the second page the favoirite coins'
I tried to copy paste the code from the first component to the second component and to import the variable, but that didnt work. I am using react for a week now.So sorry if this question is already ask.But I cant solve this issue.
You don't need to export that variable in order to pass data between components. You can use props in-order to do so.
Here is the link to the docs.
And here is an example of doing so:
// COMPONENT
const MyNameComponent = (props) => <h1>{props.name}</h1>;
// USAGE
const App = () => {
const name = "John Doe";
return <MyNameComponent name={name} />
}
As a solution to your problem could be:
<FavoriteCrypto favourite={favouriteRender} />
and using it inside the component to display it. You can align the data according to your wish. Read the docs for more info 👍.

I don't know why I get this, if it is according to the React manual

I tell him I am transferring an event from the component
child ( ItemCount) to the parent component parent ItemDetail the onADD event that only acts if an item is passed to it and when it does, the state becomes true.
The child has an event called add to cart which triggers the event and passes a product counter.
It runs perfectly but it throws me a warning that is the following.
react-dom.development.js:86 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
Can you tell me the mistake and what I did wrong? from now very grateful
I share the codes Thanks
ItemCount (component child)
import React, { useState, useContext} from 'react';
import 'materialize-css/dist/css/materialize.css';
import '../App.css';
import {FontAwesomeIcon} from '#fortawesome/react-fontawesome';
import {faPlus, faMinus, faPowerOff} from '#fortawesome/free-solid-svg-icons';
import {contextoProducto} from './ProductContext';
import swal from 'sweetalert';
const ItemCount = ({item, stockInitial, initial = 0, onAdd}) => {
const [contador, setContador] = useState(initial)
const [stock, setStock] = useState(stockInitial)
const { addProduct } = useContext(contextoProducto);
const sumar = () => {
setContador(contador + 1)
setStock(stock - 1);
avisarStock();
}
const restar= () => {
if(contador > 0){
setContador(contador - 1);
setStock(stock + 1);
}
else
{
setContador(0);
}
}
const reset = () =>{
setContador(0);
setStock(stockInitial);
}
const avisarStock = () => {
if(stock > 0 ){
}
else{
swal('No podemos enviar su envio no hay stock', "Gracias", "error");
setStock(0);
setContador(contador)
}
}
const agregarAlCarrito = () => {
onAdd(contador);
}
return(
<div>
<div className=" row left text">Stock: {stock}</div>
<article>{contador}</article>
<div className="buttonCount">
<button onClick={sumar}>
<FontAwesomeIcon icon ={faPlus}/>
</button>
<button onClick={restar}>
<FontAwesomeIcon icon={faMinus}/>
</button>
<button onClick={reset}>
<FontAwesomeIcon icon={faPowerOff}/>
</button>
<br/><h2>{avisarStock}</h2>
<button onClick={() => addProduct({...item, quantity: contador}) || agregarAlCarrito()} > Agregar al carrito </button>
</div>
</div>
)
}
export default ItemCount;
ItemDetail (component father)
import React, { useState } from "react";
import '../App.css';
import 'materialize-css/dist/css/materialize.css';
import Count from './ItemCount';
import { Link } from "react-router-dom";
export const ItemDetail = ({item}) => {
const [itemSell, setItemSell] = useState(false);
const onAdd = (count) => {
setItemSell(true);
}
return (
<main className="itemsdetails">
<div className="row" id= {item.id}>
<div className="col s12 m6">
<img src={item.image} alt="item" className="itemImg responsive-img"/>
</div>
<div className="col s12 m6">
<div className="col s12">
<h5 className="itemName">{item.title}</h5>
</div>
<div className="col s12">
<p className="itemDescription">{item.description}</p>
</div>
<div className="col s12">
<p className="itemPrice"> {item.price}</p>
</div>
<div className="col s12">
{
itemSell ? <Link to="/cart"><button className="waves-effect waves-light btn-large">Finalizar Compra</button></Link> : <Count item= {item} stockInitial={item.stock} onAdd= { onAdd } />
}
</div>
</div>
</div>
</main>
)
};
export default ItemDetail;
<br/><h2>{avisarStock}</h2>
Here, you are trying to render a component, but actually avisarStock is a function which sets state and opens an alert. It makes no sense to try to render this function.
It would appear you meant to render stock not avisarStock. This would show your stock state in the <h2>:
<br/><h2>{stock}</h2>
<br/><h2>{avisarStock}</h2> avisarStock is a function, and since Component can be function, react thinks you are doing Component instead of <Component />

How to mirror the state from switch button with ReactJS?

I'm still a beginner with ReactJS and I need to mirror my switch button in my application.
My switch button change the language from my application, and I have the same button in the header and footer of my pages.
When I change the language from the site, the another button doesn't change at the same time, for example, if I click in my header component to change the language, the button in my footer stay the same way.
I put this example into codesandbox.io
Can you tell me how do I fix the buttons?
import "./styles.scss";
import { I18nProvider } from "./providers/i18n";
import ToggleLanguage from "./components/ToggleLanguage/ToggleLanguage.js";
export default function App() {
return (
<I18nProvider>
<div className="App">
<h3>Example Header</h3>
<ToggleLanguage />
<div style={{ margin: "20px 0" }} />
<h3>Example Footer</h3>
<ToggleLanguage />
</div>
</I18nProvider>
);
}
import React from "react";
import "./ToggleLanguage.scss";
// providers
import { AppContext } from "../../providers/app";
import { saveToStorage } from "../../utils/localStorage";
const ToggleLanguage = () => {
const { state, dispatch } = React.useContext(AppContext);
const onToggleSiteLang = (siteLang) => () => {
dispatch({ type: "setLang", siteLang });
saveToStorage("siteLang", siteLang);
};
return (
<div className="toggle-language">
<label className="switch">
<input
onChange={() => onToggleSiteLang(state.siteLang)}
className="switch-checkbox"
type="checkbox"
/>
<div className="switch-button" />
<div className="switch-labels">
<span>PT</span>
<span>EN</span>
</div>
</label>
</div>
);
};
export default ToggleLanguage;
Thank you very much in advance for any help/tip.
Just control your checkbox with your state. checked={state.siteLang === 'en'}
import React from "react";
import "./ToggleLanguage.scss";
// providers
import { AppContext } from "../../providers/app";
import { saveToStorage } from "../../utils/localStorage";
const ToggleLanguage = () => {
const { state, dispatch } = React.useContext(AppContext);
const onToggleSiteLang = (siteLang) => () => {
dispatch({ type: "setLang", siteLang });
saveToStorage("siteLang", siteLang);
};
return (
<div className="toggle-language">
<label className="switch">
<input
onChange={() => onToggleSiteLang(state.siteLang)}
className="switch-checkbox"
type="checkbox"
checked={state.siteLang === 'en'}
/>
<div className="switch-button" />
<div className="switch-labels">
<span>PT</span>
<span>EN</span>
</div>
</label>
</div>
);
};
export default ToggleLanguage;
Let me know if this works for you

How do I scroll into a item in a list by search operation using react?

So, I made a react app that displays a list of items from a json file as in the pic.
I want to implement a search feature where i can enter the name and it checks for the name in list and scrolls to it.
A person told me about scroll-into-view , but I'm not understand how to make it compare the search term to the names in list.
My App.js code
import React,{useState} from 'react';
import Notes from './Notes';
import './App.css';
function App() {
const [notes] = useState([]);
const handleSubmit= ()=>{
//Upon submitting I want the search functionality to be implemented here . If thats the way to do it.
}
return (
<div className="App">
<div className="App-header">
<form><input type="text" placeholder="Start Typing.." onSubmit={handleSubmit} ></input></form>
<div className="pageTitle">Song Notes :</div>
<Notes thisNotes={notes}/>
</div>
</div>
);
}
export default App;
My Notes.js code:
import React from 'react';
const Notes = ({notes})=>{
const jsonNotes = require('./Notes.json');
const songNotes = jsonNotes.map(note => {
return(
<div key={note.id}>
<li class="noteAsList">
<div className="songTitle">{note.Name}</div>
<pre><br></br>{note.Notes}</pre>
</li>
</div>
)
})
return(
<div className="noteStyle">
{songNotes}
</div>
)
}
export default Notes;
I'm looking to implement such a feature. Either scrolling into view in the page or just displaying the item I asked for.
Thanks for the help in advance.
Codesandbox
My App.js code
import React, { useState } from "react";
import Notes from "./Notes";
import "./App.css";
const jsonNotes = require("./Notes.json");
const App = () => {
const [notes] = useState([]);
const handleSubmit = event => {
if (event.key === "Enter") {
console.log(event.target.value);
const obj = jsonNotes.find(item => item.Name === event.target.value);
const el = document.getElementById(obj.id);
if (el)
el.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "center"
});
}
};
return (
<div className="App">
<div className="App-header">
<input
type="text"
placeholder="Start Typing.."
onKeyPress={handleSubmit}
/>
<div className="pageTitle">Song Notes :</div>
<Notes thisNotes={notes} />
</div>
</div>
);
};
export default App;
My Notes.js code:
import React from "react";
const jsonNotes = require("./Notes.json");
const Notes = ({ notes }) => {
const songNotes = jsonNotes.map(note => {
return (
<div id={note.id} key={note.id}>
<li className="noteAsList">
<div className="songTitle">{note.Name}</div>
<pre>
<br />
{note.Notes}
</pre>
</li>
</div>
);
});
return <div className="noteStyle">{songNotes}</div>;
};
export default Notes;

Categories