Share the useState between two adjacent components in React - javascript

I need help, is there any possible way to send the useEffect submittedInput from search.js to AllThemeContext.js to use it as value of Provider ? Both are in two separated files.
Please I asked this question and none has responded please help me.
I don't want to move the search to context i want them to stay in separated files.
/Search js/
/*Import*/
import React, { useState } from "react";
import "./Search.scss";
/*Component*/
const Search = () => {
const [input, setInput] = useState("");
const [submittedInput, setSubmittedInput] = useState("");
const onFormSubmit = (e) => {
e.preventDefault();
setInput("");
};
return (
<>
<div className="Search">
<form onSubmit={onFormSubmit} className="Search__form">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
type="text"
placeholder=" Title, companies, expertise, or benefits"
style={{ fontFamily: "Poppins, FontAwesome" }}
></input>
<button onClick={() => setSubmittedInput(input)}>Search</button>
</form>
</div>
</>
);
};
export default Search;
AllThemeContext:
import React, { createContext, useState } from "react";
export const AllContext = createContext();
const AllContextProvider = (props) => {
const [input, setInput] = useState();
const [numbs, setNumbs] = useState(1);
return (
<AllContext.Provider value={{ input, numbs }}>
{props.children}
</AllContext.Provider>
);
};
export default AllContextProvider;

Related

How to used React-transliterate in div contentEditable custom Component

How can add React Transliterate in div contentEditable.. Please help me
import './App.css';
import EditText from "./component/EditText"
import Tools from "./component/tools"
import Header from "./component/header"
import Img from "./component/img"
import './scss/style.scss';
import MyImage from './home.png';
import React, { useState } from "react";
import { ReactTransliterate, Language } from "react-transliterate";
const App = () => {
const [text, setText] = useState("");
const [message, setMessage] = useState('');
const handleKeyDown = event => {
console.log(event.key);
if (event.key === 'Enter') {
event.preventDefault();
console.log(message);
console.log(event.target.value)
console.log('User pressed Enter ');
}
};
// const [lang, setLang] = useState<Language>("hi");
return (
<div className="App">
<Header/>
<div className='App_leftbar'>
<ul>
<li>
<a href='#'><img src={MyImage} /></a>
</li>
</ul>
</div>
<div className='App_centerbar'>
<div
contentEditable="true"
id="message"
name="message"
value={text}
onChange={event => setText(event.target.value)}
onKeyDown={handleKeyDown}
/>
<ReactTransliterate
renderComponent={(props) => <EditText onChange={event => setText(event.target.value)}
onKeyDown={handleKeyDown} {...props} />}
value={text}
onChangeText={(text) => {
setText(text);
}}
lang="hi"
placeholder="Start typing here..."
id="react-transliterate-input"
/>
<Img src={MyImage}/>
</div>
<div className='App_rightbar'>
<Tools />
</div>
</div>
);
}
export default App;
I used this npm https://www.npmjs.com/package/react-transliterate?activeTab=readme
import React, { useState } from "react";
import { ReactTransliterate } from "react-transliterate";
import "react-transliterate/dist/index.css";
const App = () => {
const [text, setText] = useState("");
return (
<ReactTransliterate
value={text}
onChangeText={(text) => {
setText(text);
}}
lang="hi"
/>
);
};
export default App;
React Transliterate uses the event.keycode property to detect keys. Here are some predefined keys you can use. Or, you can enter the integer codes for any other key you'd like to use as the trigger

REACT Why do I get the error "Uncaught TypeError: createTask is not a function" when calling a function passed as a parameter?

I am getting this error when passing a function as props to a component. But I can't figure out what's going on. Thanks in advance
TaskForm
import { useState } from "react";
function TaskForm(createTask) {
const [title, setTitle] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
const newTask = {
title,
};
createTask(newTask);
};
return (
<form onSubmit={handleSubmit}>
<input
placeholder="Escribe tu tarea"
onChange={(e) => setTitle(e.target.value)}
/>
<button>Guardar</button>
</form>
);
}
export default TaskForm;
App
import TaskList from "./TaskList";
import TaskForm from "./TaskForm";
import { tasks as data } from "./tasks";
import { useState, useEffect } from "react";
function App() {
const [tasks, setTasks] = useState([]);
useEffect(() => {
setTasks(data);
}, []);
function createTask(task) {
setTasks([...tasks, task]);
}
return (
<>
<TaskForm createTask={createTask} />
<TaskList tasks={tasks} />
</>
);
}
export default App;
Try to get data from props via destructuring as we are getting props as object
import {useState} from 'react'
function TaskForm({ createTask }) {
const [title, setTitle] = useState('');
const handleSubmit = (e) =>{
e.preventDefault();
const newTask = {
title
};
createTask(newTask)
}
return (
<form onSubmit={handleSubmit}>
<input placeholder="Escribe tu tarea"
onChange={(e)=> setTitle(e.target.value)}
/>
<button>
Guardar
</button>
</form>
)
}
or you can try as:
import {useState} from 'react'
function TaskForm(props) {
const { createTask } = props;
const [title, setTitle] = useState('');
const handleSubmit = (e) =>{
e.preventDefault();
const newTask = {
title
};
createTask(newTask)
}
return (
<form onSubmit={handleSubmit}>
<input placeholder="Escribe tu tarea"
onChange={(e)=> setTitle(e.target.value)}
/>
<button>
Guardar
</button>
</form>
)
}
App.js
import { useState } from "react";
import TaskForm from "./component/Comp1";
import TaskList from "./component/Comp2";
import "./styles.css";
export default function App() {
const [tasks, setTasks] = useState([]);
const creteTask = (newTasks) => {
setTasks([...tasks, newTasks]);
};
return (
<div className="App">
<TaskForm creteTask={creteTask} />
<TaskList tasks={tasks} />
</div>
);
}
TaskForm.js
import { useState } from "react";
export default function TaskForm({ creteTask }) {
const [title, setTitle] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
creteTask(title);
setTitle("");
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
placeholder="Escribe tu tarea"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<button>Guardar</button>
</form>
</div>
);
}
TaskList.js
export default function TaskList({ tasks }) {
console.log(tasks);
return (
<div>
<h3>Tasks</h3>
{tasks.map((task, i) => (
<p key={i}>{task}</p>
))}
</div>
);
}

JSX in fuction donot update state

Can anyone give an answer?
Unable to update the state when I click getbtn -> placeRange pass jsx to setbtn ->then unable to update the State when Silde the Range.
import React, { useState } from "react";
export default function Stack() {
const [value, setvalue] = useState(0);
const [btn, setbtn] = useState(<></>);
function placeRange() {
const jsx = (
<>
<input
type="range"
onChange={(e) => {
setvalue(e.target.value);
}}
/>
<h1>{value}</h1>
</>
);
setbtn(jsx);
}
return (
<>
<button onClick={placeRange}>getrange</button>
{btn}
</>
);
}
This seems to be working for me.
Here's a working example at codesandbox
import { useState } from "react";
export default function App() {
const [value, setvalue] = useState(0);
const [btn, setbtn] = useState(<></>);
function placeBtn() {
const jsx = (
<>
<button
onClick={() => {
setvalue(1);
}}
>
Convert to 1
</button>
</>
);
setbtn(jsx);
}
return (
<>
<h1>{value}</h1>
<button onClick={placeBtn}>getbtn</button>
{btn}
</>
);
}
Not sure I fully understand what you are trying to achieve, this is not clear enough for me.
From your code it seems you are trying to set an input range in place when clicking the button, then, you want this range to update the number below it.
If this is the case I suggest the following solution:
import React, { useState } from "react";
export default function Stack() {
const [value, setvalue] = useState(0);
const [showRange, setShowRange] = useState(false);
function placeRange() {
setShowRange(!showRange);
}
return (
<>
<button onClick={placeRange}>getrange</button>
{showRange && (
<>
<input
type="range"
onChange={(e) => {
setvalue(e.target.value);
}}
/>
<h1>{value}</h1>
</>
)}
</>
);
}

React Redux - app/store resets after added item to store

I cant figure out why when I add an item to my store the app resets. I can see for a split second that its being added to my list but then I can see all my component flicker and reload. Inspecting the console doesn't bring up any warnings.
I also plugged in just my addProduct component and productsSlice into the redux template and it also reloaded the app.
Basic HTML for adding a product with hooks:
import React, { useState } from 'react'
import { useDispatch } from 'react-redux'
import { addProduct } from '../_reducers/productsSlice'
const AddProduct = () => {
const [title, setTitle] = useState('');
const [description, setDescription] = useState('')
const [price, setPrice] = useState('')
const onTitleChanged = e => setTitle(e.target.value);
const onDescriptionChanged = e => setDescription(e.target.value);
const onPriceChanged = e => setPrice(e.target.value);
const dispatch = useDispatch();
return (
<section>
<h2>Add a new Product</h2>
<form>
<label htmlFor="Title">Title</label>
<input
type="text"
name="title"
value={title}
onChange={onTitleChanged} />
<label htmlFor="Price">Price</label>
<input
type="text"
value={price}
onChange={onPriceChanged} />
<label htmlFor="Description">Description</label>
<textarea
value={description}
onChange={onDescriptionChanged} />
<button onClick={() => dispatch(addProduct({
title: title,
price: price,
description: description
}))}>
Submit
</button>
</form>
</section>
)
}
export default AddProduct;
My Reducer:
import { createSlice } from '#reduxjs/toolkit'
const initialProductsState = [
// { name: '1', price: 10, description: 'testDescrip1' },
// { name: '2', price: 20, description: 'testDescrip2' },
// { name: '3', price: 30, description: 'testDescrip3' },
{ name: '4', price: 40, description: 'testDescrip4' }]
export const productsSlice = createSlice({
name: 'products',
initialState: initialProductsState,
reducers: {
addProduct: (state, action) => {
state.push(action.payload)
},
}
})
export const { addProduct } = productsSlice.actions;
export default productsSlice.reducer
Listing of the products:
import React from 'react';
import { useSelector } from 'react-redux'
import { Row, Col } from 'react-bootstrap'
import ProductItem from "./ProductItem"
const ProductList = () => {
const products = useSelector(state => state.products)
let numberRendered = 3;
const renderedProducts = products.map(item => (
<ProductItem product={item} />
))
return (
<div id="ProductList">
<Row>
<Col>
{renderedProducts}
</Col>
</Row>
</div>
)
}
export default ProductList;
And the product component styled with react-bootstrap:
import React from 'react';
import {productSlice} from '../_reducers/productsSlice';
import { Card, Col, Row } from 'react-bootstrap'
const ProductItem = (props) => {
return (
<Card>
<Card.Body>
<Row>
<Col md={4}>
<Card.Img variant="float" src={process.env.PUBLIC_URL + 'placeholder.png'} />
</Col>
<Col md={8}>
<Card.Title>{props.product.title}</Card.Title>
<Card.Text>{props.product.description}</Card.Text>
<Card.Subtitle>{props.product.price}</Card.Subtitle>
</Col>
</Row>
</Card.Body>
</Card>
)
}
export default ProductItem;
store:
import { configureStore } from '#reduxjs/toolkit'
import productsSlice from '../src/_reducers/productsSlice'
const store = configureStore({
reducer: {
products: productsSlice,
}
})
export default store;
Pretty sure you just need to add an event.preventDefault() to the form's submit event
import React, { useState } from 'react'
import { useDispatch } from 'react-redux'
import { addProduct } from '../_reducers/productsSlice'
const AddProduct = () => {
const [title, setTitle] = useState('');
const [description, setDescription] = useState('')
const [price, setPrice] = useState('')
const onTitleChanged = e => setTitle(e.target.value);
const onDescriptionChanged = e => setDescription(e.target.value);
const onPriceChanged = e => setPrice(e.target.value);
const dispatch = useDispatch();
const handleSubmit = (e) => {
e.preventDefault();
dispatch(addProduct({
title: title,
price: price,
description: description
}))
}
return (
<section>
<h2>Add a new Product</h2>
<form onSubmit={handleSubmit}>
<label htmlFor="Title">Title</label>
<input
type="text"
name="title"
value={title}
onChange={onTitleChanged} />
<label htmlFor="Price">Price</label>
<input
type="text"
value={price}
onChange={onPriceChanged} />
<label htmlFor="Description">Description</label>
<textarea
value={description}
onChange={onDescriptionChanged} />
<button type="submit">
Submit
</button>
</form>
</section>
)
}
export default AddProduct;
Without the preventDefault submitting the form will submit a get request to the same route, which will cause the component to reload.

TypeError setEmail is not a function

Trying to create sign in and sign up with react and firebase and got the error setEmail is not a function when trying to fill the input for the email, if i try to fill the input for password, i get the same error but for setPassword setPassword is not a function App.js
Here is my app.js
import React, {useState, useEffect} from 'react';
import './App.css';
import './Components/Feed/styles/_properties.scss'
import Home from './Pages';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import SignInPage from './Pages/signin';
import SignUpPage from './Pages/signup';
import Feed from './Pages/feed';
import fire from './fire';
function App() {
const [user, setUser] = useState('');
const [email, setEmail] = useState('');
const [ password, setPassword] = useState('');
const [emailError, setEmailError] = useState('');
const [passwordError, setPasswordError] = useState('');
const [hasAccount, setHasAccount] = useState('');
const clearInputs = () => {
setEmail('')
setPassword('');
}
const clearErrors = () => {
setEmailError('');
setPasswordError('');
}
const handleLogin = () => {
clearErrors();
fire
.auth()
.signInWithEmailAndPassword(email,password)
.catch(err => {
switch(err.code){
case 'auth/Invalid-email':
case 'auth/user-disabled':
case 'auth/user-not-found':
setEmailError(err.message);
break;
case 'auth/wrong-password':
setPasswordError(err.message);
break;
}
});
};
const handleSignUp = () => {
clearErrors();
fire
.auth()
.createuserWithEmailAndPassword(email,password)
.catch(err => {
switch(err.code){
case 'auth/email-already-In-use':
case 'auth/invalid-email':
setEmailError(err.message);
break;
case 'auth/weak-password':
setPasswordError(err.message);
break;
};
});
};
const handleLogout = () => {
fire.auth().signOut();
};
const authListener = () => {
fire.auth().onAuthStateChanged(user =>{
if(user){
clearInputs();
setUser(user);
}else{
setUser('')
};
});
};
useEffect(() => {
authListener();
}, []);
return (
<Router>
<Switch>
{user ? (
<Home handleLogout={handleLogin}/>
):(
<SignInPage email={email}
setEmail={setEmail}
emailError ={emailError}
setEmailError ={setEmailError}
password={password}
setPassword={setPassword}
handleLogin={handleLogin}
handleSignUp={handleSignUp}
hasAccount={hasAccount}
setHasAccount={setHasAccount}
passwordError={passwordError}/>
)}
<Route path='/signup' component={SignUpPage} exact />
<Route path = '/feed' component={Feed} exact />
</Switch>
</Router>
);
}
export default App;
And here is my Signin.js
import React from 'react';
import './SigninElements.css'
const SignIn = (props) => {
const {
email,
setEmail,
password,
setPassword,
handleSignIn,
handleSignup,
hasAccount,
setHasAccount,
emailError,
passwordError
} = props;
return (
<section className='signin'>
<div className='signinContainer'>
<label>Username or Email</label>
<input
type='text'
outoFocus
required
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<p className='errorMsg'>{emailError}</p>
<label>Password</label>
<input
type='password'
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<p className='errorMsg'>{passwordError}</p>
<div className='btnContainer'>
{hasAccount ? (
<>
<button onClick={handleSignIn}> Sign In</button>
<p> Don't have an account ? <span onclick={() => setHasAccount(!hasAccount)}>Sign up</span></p>
</>
) : (
<>
<button onClick={handleSignup}> Sign In</button>
<p> Have an account ? <span onClick={() => setHasAccount(!hasAccount)}>Sign in</span></p>
</>
)}
</div>
</div>
</section>
)
}
export default SignIn;
I searched what could be the problem, but I have no idea. I think it could be the way I'm calling the props. I might be wrong lol. I would really appreciate any help.
Because you are using the setEmail prop as a function, but not passing it that way. That's why you are getting that error. Try in a following way.
<SignInPage setEmail={setEmail} .../>
And in SignInPage change the code to
onChange={handleChange}
const handleChange = (e) => {
props.setEmail(e.target.value);
}
or
onChange={(e) => props.setEmail(e.target.value)}

Categories

Resources