How to used React-transliterate in div contentEditable custom Component - javascript

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

Related

React giving a blank white page on rendering the Chat component, after integrating firebase for messages

I am creating a chat app. The app returns a blank page after the login page, instead of showing the chat section. The problem is with the firebase code which I used for getting the messages from the firebase database. If I don't render the Chat section, then the Sidebar section turns out to render well. The Chat component code is:
import React, { useEffect, useState } from "react";
import "./Chat.css";
import { Avatar, IconButton } from "#material-ui/core";
import { SearchOutlined } from "#material-ui/icons";
import { AttachFile } from "#material-ui/icons";
import MoreVertIcon from "#material-ui/icons/MoreVert";
import MicIcon from "#material-ui/icons/Mic";
import InsetEmoticonIcon from "#material-ui/icons/InsertEmoticon";
import { useParams } from "react-router-dom";
import db from "./firebase";
function Chat() {
const [input, setInput] = useState("");
const [photo, setphoto] = useState("");
const [messages, setMessages] = useState();
const { roomId } = useParams();
const [roomName, setRoomName] = useState();
useEffect(() => {
if (roomId) {
console.log("Change");
db.collection("rooms")
.doc(roomId)
.onSnapshot((snapshot) => setRoomName(snapshot.data().name));
db.collection("rooms")
.doc(roomId)
.collection("messages")
.orderBy("timestamp", "asc")
.onSnapshot((snapshot) =>
setMessages(snapshot.docs.map((doc) => doc.data()))
);
}
}, [roomId]);
useEffect(() => {
setphoto(Math.floor(Math.random() * 5000));
}, []);
const sendMessage = (e) => {
e.preventDefault();
console.log("You typed a message");
setInput("");
};
return (
<div className="chat">
<div className="chat-header">
<Avatar
src={`https://avatars.dicebear.com/api/pixel-art/${photo}.svg`}
/>
<div className="chat-headerInfo">
<h2>{roomName}</h2>
<p>Last Seen</p>
</div>
<div className="chat-headerRight">
<IconButton>
<SearchOutlined />
</IconButton>
<IconButton>
<AttachFile />
</IconButton>
<IconButton>
<MoreVertIcon />
</IconButton>
</div>
</div>
<div className="chat-body">
{messages.map((message) => (
<p className="chat-message chatReceiver">
<span className="sender">{message.name}</span>
{message.message}
<span className="timestamp">
{new Date(message.timestamp?.toDate()).toUTCString}
</span>
</p>
))}
</div>
<div className="chat-footer">
<InsetEmoticonIcon />
<form>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
type="text"
placeholder="Type a message"
/>
<button onClick={sendMessage} type="submit">
Send a message
</button>
</form>
<MicIcon />
</div>
</div>
);
}
export default Chat;
Github link of the project : https://github.com/aditramdas/Chat-App/tree/main/chat-app-new/src

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>
);
}

Getting an error "Each child in a list should have a unique "key" prop."

I am currently learning React by following a video by Clever Programmer
(https://www.youtube.com/watch?v=pUxrDcITyjg&list=PLvmRwCtZ6YKRBCjKGNEbmOd816fgvptZc&index=17&t=20s)
However, towards the end I am finding an error which is not openly reported in comments or threads.
I have localised it to the following file "Chat.js" which contains the below code.
My question is: What could be tripping the error "Each child in a list should have a unique "key" prop.".
Advice or solution would be great, but if solved, please provide reasoning as I will need to learn why it was not working!
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import "./Chat.css";
import { useStateValue } from "./StateProvider.js";
import { Avatar, IconButton } from "#material-ui/core";
import {
AttachFile,
InsertEmoticon,
Mic,
SearchOutlined,
} from "#material-ui/icons";
import MoreVert from "#material-ui/icons/MoreVert";
import db from "./firebase";
import firebase from 'firebase/compat/app';
function Chat() {
const [input, setInput] = useState("");
const [seed, setSeed] = useState("");
const { roomId } = useParams();
const [roomName, setRoomName] = useState("");
const [messages, setMessages] = useState([]);
const [{ user }, dispatch] = useStateValue();
useEffect(() => {
if (roomId) {
db.collection("rooms")
.doc(roomId)
.onSnapshot((snapshot) => setRoomName(snapshot.data().name));
db.collection('rooms')
.doc(roomId)
.collection("messages")
.orderBy('timestamp', 'asc')
.onSnapshot(snapshot =>
setMessages(snapshot.docs.map(doc => doc.data()))
);
}
}, [roomId]);
useEffect(() => {
setSeed(Math.floor(Math.random() * 5000));
}, [roomId]);
const sendMessage = (e) => {
e.preventDefault();
console.log("You typed: >>>", input);
db.collection('rooms').doc(roomId).collection('messages').add({
message: input,
user: user.displayName,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
})
setInput("");
};
return (
<div className="chat">
<div className="chat__header">
<Avatar src={`https://avatars.dicebear.com/api/human/${seed}.svg`} />
<div className="chat__headerInfo">
<h3>{roomName}</h3>
<p>Last seen...</p>
</div>
<div className="chat__headerRight">
<IconButton>
<SearchOutlined />
</IconButton>
<IconButton>
<AttachFile />
</IconButton>
<IconButton>
<MoreVert />
</IconButton>
</div>
</div>
{/* The div "chat__body" incorporates the entire message structure */}
<div className="chat__body">
{messages.map((message) => (
<p className={`chat__message ${message.name === user.displayName && "chat__receiver"}`}>
<span className="chat__name">{message.name}</span>
{message.message}
<span className="chat__timeStamp">
{new Date(message.timestamp?.toDate()).toUTCString()}
</span>
</p>
))}
</div>
<div className="chat__footer">
<InsertEmoticon />
<form>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type a message"
type="text"
/>
<button onClick={sendMessage} type="submit">
Send a message
</button>
</form>
<Mic />
</div>
</div>
);
}
export default Chat;
messages.map is returning a list, and each item in it must have a unique key value that identifies it.
Either from an id from the current item
messages.map((message) => (
<p key={message.id} className...
or the current index
messages.map((message, i) => (
<p key={i} className...

Modal reseting the redux state

I made a react/redux application using firebase, but when i open the modal and close it or add a product all data of application are set hidden
App.js file
import React, { useState } from "react";
import "./App.css";
import Layout from "./components/Layout/Layout";
import Header from "./components/Header/Header";
import FormModal from "./components/Modal/FormModal";
import Modal from "./components/Modal/Modal";
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import ProductReducer from "./reducers/ProductReaducer";
import Card from "./components/Card/Card";
function App() {
const store = createStore(ProductReducer);
const [showModal, setShowModal] = useState(false);
const onShowModal = () => {
setShowModal(true);
};
const onHideModal = () => {
setShowModal(false);
};
return (
<div>
<Provider store={store}>
<Header onShowModal={onShowModal} />
<Layout>
<Card />
</Layout>
<Modal show={showModal}>
<FormModal show={showModal} onHideModal={onHideModal} />
</Modal>
</Provider>
</div>
);
}
export default App;
Modal.js file
import React from "react";
import { useSelector } from "react-redux";
const Modal = (props) => {
const states = useSelector((state) => state);
console.log(states);
return (
<div
className={
props.show
? `bg-slate-400 fixed top-0 left-0 w-screen h-screen flex justify-center items-center z-1`
: "hidden"
}
>
{props.children}
</div>
);
};
export default Modal;
FormModal.js file
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { addItem } from "../../actions/ProductActions";
import { collection, addDoc, getFirestore } from "firebase/firestore";
const FormModal = (props) => {
const [infoProduct, setInfoProduct] = useState({
title: "",
url: "",
description: "",
price: 0,
});
const handleChange = (evt) => {
const targetValue = evt.target.value;
const key = evt.target.name;
setInfoProduct((old) => ({
...old,
[key]: targetValue,
}));
};
const dispatch = useDispatch();
const db = getFirestore();
const addProduct = async () => {
try {
const docRef = await addDoc(collection(db, "webjump-store"), productItem);
dispatch(addItem(infoProduct));
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
};
const productItem = {
produto: {
title: infoProduct.title,
url: infoProduct.url,
description: infoProduct.description,
price: infoProduct.price,
},
};
return (
<div className={props.show ? "bg-slate-300 w-64 p-6 z-1" : "hidden"}>
{" "}
<button type="button" className="float-right" onClick={props.onHideModal}>
X
</button>
<form className="flex flex-col items-center">
<label>Title</label>
<input
className="my-3"
type="text"
name="title"
onChange={handleChange}
/>
<label>Url</label>
<input
className="my-3"
type="text"
name="url"
onChange={handleChange}
/>
<label>Description</label>
<input
className="my-3"
type="text"
name="description"
onChange={handleChange}
/>
<label>Price</label>
<input
className="my-3"
type="text"
name="price"
onChange={handleChange}
/>
<button
className="my-4 p-4 bg-slate-200 border-2 border-solid border-black"
type="button"
onClick={addProduct}
>
Add Product
</button>
</form>
</div>
);
};
export default FormModal;
I have no ideia o it can be.
When i do a console.log in my redux state it appers to be empty.
But when i reload the page all data from fire store appears again.

Share the useState between two adjacent components in React

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;

Categories

Resources