Local Image Upload Error in react-email-editor - reactjs

I have integrated the react-email-editor into react, and when I upload an image from my local (size less than 500kb) It shows failed to upload image.
Please help, Below is the screen shot.
image
import { useRef, useState } from "react";
import EmailEditor from 'react-email-editor';
import sample from "./sample.json";
function App() {
const emailEditorRef = useRef(null);
const [json,SetJson]=useState();
const exportHtml = () => {
emailEditorRef.current.editor.exportHtml((data) => {
const { design, html } = data;
console.log('exportHtml', html);
console.log('design', design.body);
});
emailEditorRef.current.editor.saveDesign((design) => {
console.log("saveDesign", JSON.stringify(design, null, 4));
alert("Design JSON has been logged in your developer console.");
});
};
const onLoad = () => {
// editor instance is created
// you can load your template here;
const templateJson = sample;
emailEditorRef.current.editor.loadDesign(templateJson);
}
const onReady = () => {
// editor is ready
console.log('onReady');
};
return {
<div>
<div>
<button onClick={exportHtml}>Export HTML</button>
</div>
<div style={{width:"70vw"}}>
<EmailEditor ref={emailEditorRef} onLoad={onLoad} />
</div>
</div>
}
}
export default App;

Related

EditorJS is not showing in NextJS even it is loaded through SSR:false

so I am integrating EditorJs with the NextJs app I have done the initialization in the console it shows Editojs is ready but on the screen, it is not visible
can anyone please tell me what I am doing wrong I am sharing my code below
Editor.js
import { createReactEditorJS } from 'react-editor-js'
import { EditorTools } from './EditorTools';
import React, { useEffect } from 'react'
const Editor = () => {
const ReactEditorJS = createReactEditorJS();
return (
<div>
<ReactEditorJS holder="customEditor" tools={EditorTools}>
<div id="customEditor" />
</ReactEditorJS>
</div>
)
}
export default Editor
EditorTools.js
import Header from '#editorjs/header';
export const EditorTools = {
header: {
class: Header,
config: {
placeholder: 'Let`s write an awesome story! ✨',
},
},
};
Create.js
import React from 'react'
import dynamic from 'next/dynamic';
const EditorJSNoSSRWrapper = dynamic(import('../../../components/Editor/Editor'), {
ssr: false,
loading: () => <p>Loading ...</p>,
});
const create = () => {
return (
<div>
<EditorJSNoSSRWrapper />
</div>
)
}
export default create

Torch working on Android but not in iOS (ReactJS)

I'm building a QR scanner inside a ReactJS web app that is supposed to run on both Android and iOS. However, I cannot get the torch/flashlight to work on iOS.
I'm using the #blackbox-vision toolbox to handle both the torch and the QR scanner. As far as I understand you need to start the camera functionality and can use the video stream to manipulate the torch. Below code works fine on Android but not on iOS:
import { useState, useEffect, useRef } from "react";
import { QrReader } from "#blackbox-vision/react-qr-reader";
import { useTorchLight } from "#blackbox-vision/use-torch-light";
import styles from "./view.module.css";
import IconButton from "../../components/UI/iconbutton/view";
function SAQRView() {
const streamRef = useRef(null);
const [on, toggle] = useTorchLight(streamRef.current);
const [showTorchToggleButton, setShowTorchToggleButton] = useState(false);
const [msg, setMsg] = useState("");
const setRef = ({ stream }) => {
streamRef.current = stream;
setShowTorchToggleButton(true);
};
const previewStyle = {
width: "100%",
};
const onError = (error) => {
console.log(error);
};
const onTorchClick = (event) => {
toggle();
};
return (
<>
<div className={styles.container}>
<div className={styles.sub_container}>
<QrReader
delay={100}
showViewFinder={false}
style={previewStyle}
onLoad={setRef}
onError={onError}
onScan={setData}
constraints={{
facingMode: "environment",
video: true,
}}
/>
<div className={styles.footer}>
{showTorchToggleButton && (
<IconButton
icon="Flash_off"
toggleIcon="Flash_on"
isToggled={on}
onClick={onTorchClick}
/>
)}
</div>
{msg}
</div>
</div>
</>
);
}
export default SAQRView;
So then I tried manipulating the video stream manually:
import { useState, useEffect, useRef } from "react";
import { QrReader } from "#blackbox-vision/react-qr-reader";
import { useTorchLight } from "#blackbox-vision/use-torch-light";
import styles from "./view.module.css";
import IconButton from "../../components/UI/iconbutton/view";
function SAQRView() {
const streamRef = useRef(null);
const [on, toggle] = useTorchLight(streamRef.current);
const [showTorchToggleButton, setShowTorchToggleButton] = useState(false);
const [msg, setMsg] = useState("");
const setRef = ({ stream }) => {
streamRef.current = stream;
setShowTorchToggleButton(true);
};
const previewStyle = {
width: "100%",
};
const onError = (error) => {
console.log(error);
};
const onTorchClick = (event) => {
const tracks = streamRef.current.getVideoTracks();
const track = tracks[0];
setMsg(JSON.stringify(track.getCapabilities(), null, 2));
try {
if (!track.getCapabilities().torch) {
alert("No torch available.");
}
track.applyConstraints({
advanced: [
{
torch: true,
},
],
});
} catch (error) {
alert(error);
}
};
return (
<>
<div className={styles.container}>
<div className={styles.sub_container}>
<QrReader
delay={100}
showViewFinder={false}
style={previewStyle}
onLoad={setRef}
onError={onError}
onScan={setData}
constraints={{
facingMode: "environment",
video: true,
}}
/>
<div className={styles.footer}>
{showTorchToggleButton && (
<IconButton
icon="Flash_off"
toggleIcon="Flash_on"
isToggled={on}
onClick={onTorchClick}
/>
)}
</div>
{msg}
</div>
</div>
</>
);
}
export default SAQRView;
Again, this works on Android, but not iOS. Notice that I stringify the track capabilities and print them at the bottom of the screen. For Android this looks as follows:
And for iOS, it looks like this:
So it seems that iOS cannot access the torch capability. However, the torch will be greyed out when the QR scanner is active, so it does seem to grab hold of the torch.
Also we have tried installing the Chrome web browser but this gave exactly the same result.
Can I get around this and if so, how?

React - context not updating

I am learning React by taking the implementation of reading a csv file, and breaking it into separate components that share data with context.
The problem is that after the user selects a file with FileSelector component, the state in ColumnsSelector is not updated, and file object (in ColumnSelector component) is still an empty object.
Thanks
Code:
FileSelector.jsx component gets the file from the user:
import React, { useContext } from "react";
import { DataContext } from './DataContext'
// Allowed extensions for input file
const allowedExtensions = ["csv"];
const FileSelector = () => {
const newError = useContext(DataContext).newError;
const changeFile = useContext(DataContext).changeFile;
const handleFileChange = (e) => {
if (e.target.files.length) {
const inputFile = e.target.files[0];
const fileExtension = inputFile?.type.split("/")[1];
if (!allowedExtensions.includes(fileExtension)) {
newError("Please input a csv file");
return;
}
changeFile(inputFile);
}
};
return (
<div>
<label htmlFor="csvInput" style={{ display: "block" }}>
Enter CSV File
</label>
<input
onChange={handleFileChange}
id="csvInput"
name="file"
type="File"
/>
</div>
);
};
export default FileSelector;
ColumnsSelector.jxs will be updated after the user selects a file, and will return the file headers:
import React, { useContext } from "react";
import Papa from "papaparse";
import { DataContext } from './DataContext'
// Allowed extensions for input file
const allowedExtensions = ["csv"];
const ColumnsSelector = () => {
const data = useContext(DataContext).data;
const changeData = useContext(DataContext).changeData;
const error = useContext(DataContext).error;
const newError = useContext(DataContext).newError;
const file = useContext(DataContext).file; // object is empty also after user uploads a file!
const handleParse = () => {
// If user clicks the parse button without
// a file we show a error
if (!file) return newError("Enter a valid file");
// Initialize a reader which allows user
// to read any file or blob.
const reader = new FileReader();
// Event listener on reader when the file
// loads, we parse it and set the data.
reader.onload = async ({ target }) => {
const csv = Papa.parse(target.result, { header: true });
const parsedData = csv?.data;
const columns = Object.keys(parsedData[0]);
changeData(columns);
};
reader.readAsText(file);
};
return (
<div>
<div>
<button onClick={handleParse}>Parse</button>
</div>
<div style={{ marginTop: "3rem" }}>
{Object.keys(data).length === 0 ? "" : data.map((col,
idx) => <div key={idx}>{col}</div>)}
</div>
</div>
);
};
export default ColumnsSelector;
DataSelector.jsx is a container for both components
import React, { useState } from "react";
import { DataProvider } from './DataContext'
import FileSelector from './FileSelector';
import ColumnsSelector from './ColumnsSelector'
// Allowed extensions for input file
const allowedExtensions = ["csv"];
const DataSelection = () => {
// This state will store the parsed data
const [data, setData] = useState([]);
// It state will contain the error when
// correct file extension is not used
const [error, setError] = useState(null);
// It will store the file uploaded by the user
const [file, setFile] = useState("");
const providerOptions = {
data: {},
changeData: (value) => setData(value),
error: {},
newError: (value) => setError(value),
file: {},
changeFile: (value) => setFile(value),
}
return (
<div>
<DataProvider value={providerOptions}>
<FileSelector />
<ColumnsSelector/>
</DataProvider>
</div>
);
};
export default DataSelection;
app.js holds DataSelector component:
import React from 'react';
import './App.css';
import DataSelector from './DataSelector';
function App() {
return (
<div className="App">
<header className="App-header">
<div>
<DataSelector />
</div>
</header>
</div>
);
}
export default App;
DataContext.js defined the context:
import React from 'react';
export const DataContext = React.createContext({});
export const DataProvider = DataContext.Provider;
export const DataConsumer = DataContext.Consumer;

React Typescript Video Preview

I'm trying to create a video preview for a internal project, with "React & Typescript" using react hooks below is the component code,
import React, { useEffect, useRef, useState } from 'react';
import { INewVideo } from 'src/models';
import { useForm } from 'react-hook-form';
const NewVideo: React.FC = () => {
const { register, handleSubmit } = useForm<INewVideo>();
const [file, setFile] = useState<any>();
const videoChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
console.log(event.currentTarget.files![0]);
setFile(event.currentTarget.files![0])
};
useEffect(() => {
console.log("use effect", file)
}, [file])
return (<div>
<input
accept="video/mp4, video/mov"
onChange={videoChangeHandler}
type="file"
/>
{
file ? (
<div>
{file}
</div>
) : ("No Video")
}
</div>)
};
export default NewVideo;
But I'm not able to set the file, its throwing below error
I need to render upload video & give options for screen capture & trimming features. But these are later stages
You are getting this error because file is not a JSX.Element which you are trying to render in your DOM. Basically you got some Object in your file state. Either you can provide this as a source for HTML.Video Element or you can get file object data from it.
{
file ? <div> {file.name}</div> : "No Video";
}
This code should print the file name in your screen. This is the main place where you are getting some error.
Or if you want to show the preview of your recent upload video you can simply pass that file object as a HTML.Video src. Like it:
{
file ? <div> <video src={URL.createObjectURL(file)} autoPlay /></div> : "No Video";
}
This will show the preview of your video.
I've found below
import React, { useEffect, useState } from 'react';
import { INewVideo } from 'src/models';
import { useForm } from 'react-hook-form';
const NewVideo: React.FC = () => {
const { register } = useForm<INewVideo>();
const [file, setFile] = useState<any>();
const videoChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.currentTarget.files![0];
console.log("File", file);
const reader = new FileReader();
reader.addEventListener("load", () => {
setFile(reader.result);
});
reader.readAsDataURL(event.target.files![0]);
};
useEffect(() => {
console.log("use effect", file)
}, [file])
return (<div>
<input
{...register("Link")}
accept="video/mp4, video/mov"
onChange={videoChangeHandler}
type="file"
/>
<video controls src={file} />
</div>)
};
export default NewVideo;

Component not rerendering after axios Get (React)

I'm trying to render List of items of my DB using React.Context.
All my request work pretty well.
when i console log my states first I get an empty array and then array with the data that I need but my component is not updating. I have to go to another page an then go back to this page to get the data. I don't really understand why... here are my files..
ArticlesContext.js :
import React, { useState, createContext, useEffect } from 'react';
import axios from 'axios'
export const ArticlesContext = createContext();
export function ArticlesProvider(props) {
const [articles, setArticles] = useState([]);
const [user, setUser] =useState(0)
async function getArticles () {
await axios.get(`/api/publicItem`)
.then(res => {
setArticles(res.data);
})
}
useEffect( () => {
getArticles()
}, [user])
console.log(articles);
return (
<ArticlesContext.Provider value={[articles, setArticles]}>
{props.children}
</ArticlesContext.Provider>
);
}
Inventaire.js :
import React, { useContext, useEffect, useState } from 'react';
import './Inventaire.css';
import { ArticlesContext } from '../../../context/ArticlesContext';
import DeleteAlert from './Delete/Delete';
import Modify from './Modify/Modify';
import Filter from './Filter/Filter';
import axios from 'axios'
import Crud from '../../Elements/Articles/Crud/Crud';
import List from './List/List';
export default function Inventaire() {
const [articles, setArticles] = useContext(ArticlesContext);
const [filter, setFilter] = useState(articles)
console.log(articles);
//list for Inputs
const cat = articles.map(a => a.category.toLowerCase());
const categoryFilter = ([...new Set(cat)]);
const gender = articles.map(a => a.gender.toLowerCase());
const genderFilter = ([...new Set(gender)]);
//Event Listenner
//Uncheck All checkboxes
function UncheckAll() {
const el = document.querySelectorAll("input.checkboxFilter");
console.log(el);
for (var i = 0; i < el.length; i++) {
var check = el[i];
if (!check.disabled) {
check.checked = false;
}
}
}
//SearchBar
const searchChange = (e) => {
e.preventDefault();
const stuff = articles.filter((i) => {
return i.name.toLowerCase().match(e.target.value.toLowerCase())
})
setFilter(stuff)
UncheckAll(true)
}
const Types = (e) => {
if (e.target.checked === true) {
const stuff = filter.filter((i) => {
return i.category.toLowerCase().match(e.target.value.toLowerCase())
})
setFilter(stuff)
console.log(articles);
} else if (e.target.checked === false) {
setFilter(articles)
}
}
const Gender = (e) => {
if (e.target.checked === true) {
const stuff = filter.filter((i) => {
console.log(i.category, e.target.value);
return i.gender.toLowerCase().match(e.target.value.toLowerCase())
})
setFilter(stuff)
} else if (e.target.checked === false) {
setFilter(articles)
}
}
return (
<div className="inventaireContainer">
<input type="text" placeholder="Recherche un Article" onChange={searchChange} />
<div className="inventaireMenu">
<Crud />
<Filter
filter={Types}
categorys={categoryFilter}
genre={genderFilter}
target={Gender}
/>
</div>
<List filter={filter} articles={articles}/>
</div>
)
}
List.js :
import React from 'react';
import DeleteAlert from '../Delete/Delete';
import Modify from '../Modify/Modify';
export default function List({ filter, articles }) {
return (
<div>
{filter.map((details, i) => {
return (
<div className="inventaireBlock" >
<div className="inventaireGrid">
<div className="inventaireItemImg">
<img src={details.image} alt="ItemImg" />
</div>
<h2>{details.name}</h2>
<h3>{details.category}</h3>
<h3>{details.gender}</h3>
<div>
<p>S :{details.sizes[0].s}</p>
<p>M :{details.sizes[0].m}</p>
<p>L :{details.sizes[0].l}</p>
<p>XL :{details.sizes[0].xl}</p>
</div>
<h2> Prix: {details.price}</h2>
<div className="modify">
<Modify details={details._id} />
</div>
<div className="delete" >
<DeleteAlert details={details._id} articles={articles} />
</div>
</div>
</div>
)
})}
</div>
)
}
Thanks for your time

Resources