I want to open the camera of my pc via capacitor camera pluging within my react code but it fail. There is my code:
import React, { useState } from 'react';
import { Plugins, CameraResultType } from '#capacitor/core';
const App = () => {
const { Camera } = Plugins;
const [photo, setPhoto] = useState();
const takePhoto = async () => {
console.log("Launch function");
const image = await Camera.getPhoto({
quality: 90,
allowEditing: false,
resultType: CameraResultType.Uri
});
console.log(image.webPath);
setPhoto(image.webPath);
};
return (
<div className="App">
{photo ? <img src={photo} alt="test camera" /> : <span>There is no picture yet.</span>}
<button onClick={takePhoto}>Camera</button>
</div>
);
}
export default App;
and this is the error that I get:
that is my console screeshoot
I found the solution. Just install a load the ui component used to take the photo.
In the src/index.js I just add the following:
import { defineCustomElements } from '#ionic/pwa-elements/loader';
defineCustomElements(window);
that is my final resutl:
import React from 'react';
import { defineCustomElements } from '#ionic/pwa-elements/loader';
import ReactDOM from 'react-dom';
import App from './App';
defineCustomElements(window);
const app = (
<App />
)
ReactDOM.render(app, document.getElementById('root'));
Related
I am getting a No <Web3Provider ...> Found. when my React Typescript app loads and tries to call the context manager method setFirstValidConnector as described in the latest 5.0.3 web3-react here
This is the full code:
./wallet/connect.ts
import { Connectors } from 'web3-react'
const { InjectedConnector } = Connectors
const metamask = new InjectedConnector({ supportedNetworks: [1, 4] })
const alchemy = new Connectors.NetworkOnlyConnector({ providerURL: "https://eth-rinkeby.alchemyapi.io/v2/..."});
export const connectors = { metamask, alchemy }
App.tsx
import React, { useEffect } from 'react';
import Web3Provider, { useWeb3Context } from 'web3-react';
import { connectors } from './wallet/connect';
export default function App() {
const context = useWeb3Context()
useEffect(() => {
context.setFirstValidConnector(['metamask', 'alchemy']) // => No <Web3Provider ...> Found.
}, [])
return (
<Web3Provider
connectors={connectors}
libraryName={'ethers.js'}
>
<div className="App">
<ButtonAppBar />
<AboutSection />
<Workspace />
</div>
</Web3Provider>
);
};
Does anyone happen to see where I'm going wrong? Thank you!
im trying to implement matomo analytics within my react application (cra), however it trows an invalid hook call exception. Code has been copied from the simple example
https://www.npmjs.com/package/#datapunt/matomo-tracker-react
Did i miss something?
react: 17.0.2
react-dom: 17.0.2
code:
Index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import store from "./redux/store";
import { MatomoProvider, createInstance } from "#datapunt/matomo-tracker-react";
const matomo = createInstance({
urlBase: "http://192.168.133.226/",
siteId: 3,
heartBeat: {
active: true,
seconds: 10,
},
linkTracking: false,
configurations: {
disableCookies: true,
setSecureCookie: true,
setRequestMethod: "POST",
},
});
ReactDOM.render(
<MatomoProvider value={matomo}>
<Provider store={store}>
<App />
</Provider>
</MatomoProvider>,
document.getElementById("root")
);
App.js
import React, { useEffect } from "react";
import "./App.scss";
import { BrowserRouter as Router, Link } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { useMatomo } from "#datapunt/matomo-tracker-react";
import Navigation from "./components/navigation/navigation";
import Sitemap from "./components/sitemap/sitemap";
import Main from "./pages/main/main";
function App() {
const modal = useSelector((state) => state.modal);
const items = useSelector((state) => state.items);
const app = useSelector((state) => state.app);
const dispatch = useDispatch();
const { trackPageView } = useMatomo();
useEffect(() => {
trackPageView();
// eslint-disable-next-line
}, []);
return (
<div className='app'>
<Router>
<Navigation />
<Sitemap />
<Main />
</Router>
</div>
);
}
export default App;
You need to create the Matamo instance first and then wrap everything around that.
Refer this https://www.npmjs.com/package/#datapunt/matomo-tracker-react
https://github.com/jonkoops/matomo-tracker/tree/main/packages/react
Use this one & try again:
npm install #jonkoops/matomo-tracker-react
import { MatomoProvider, createInstance } from '#jonkoops/matomo-tracker-react'
import { useMatomo } from '#jonkoops/matomo-tracker-react'
i am trying to build a react native blog app with context to transfer data to any child
here is my App.js
import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import IndexScreen from './src/screens/IndexScreen';
import { BlogProvider } from './src/context/BlogContext';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='Index'>
<Stack.Screen name="Index" component={IndexScreen} options={{title: 'Blogs'}}/>
</Stack.Navigator>
</NavigationContainer>
);
}
//export default App;
export default () => {
return (
<BlogProvider>
<App/>
</BlogProvider>
)
}
here is my BlogContext.js
import React from 'react'
const BlogContext = React.createContext();
//const BlogContext = NavigationContext;
export const BlogProvider = ({ childern }) => {
return (<BlogContext.Provider>
{childern}
</BlogContext.Provider>
)
}
export default BlogContext;
Index.js
import React from 'react'
import { View, Text, StyleSheet } from 'react-native'
const IndexScreen = () => {
return (
<View>
<Text> index screen</Text>
</View>
)
}
const styles = StyleSheet.create({});
export default IndexScreen;
it is rendering on my ios simulator blank, if i don't enclose App within BlogProvider it renders successfully. i am trying to learn react native with udemy, not sure about how context work, any help would be appreciated, Thanks
You misspelled children, so nothing is actually getting rendered by BlogProvider.
I'm trying to do my exportable package in which I create the redux store. This is the code:
import React from "react";
import { Provider } from "react-redux";
import { ErrorPage } from "../components/shared";
import { MyCoreApplication } from "./MyCoreApplication";
import { configureStore } from "../tools/configureStore";
import { createCoreHelp } from "./createCoreHelp";
export const MyCore = ({ withLogs, applicationSagas, applicationReducers, app, cookieInfo }) => {
const help = createCoreHelp(applicationSagas, applicationReducers, app);
if (help.error) return <ErrorPage errorMessage={help.error} tooltipMessage={help.tooltip} />;
else {
const store = configureStore(withLogs, applicationSagas, applicationReducers);
return (
<Provider store={store}>
<MyCoreApplication app={app} cookieInfo={cookieInfo} />
</Provider>
);
}
};
MyCoreApplication is the same:
import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { IntlProvider } from "react-intl";
import { BrowserRouter as Router } from "react-router-dom";
import { CookieBar, ErrorPage, LoadingSpinner, Notification } from "../components/shared";
import { getConfig, getConfigStore, fetchConfigEnded, isMobileMode, setMobileMode } from "../modules/configuration";
import { getLocale, setLocale, getMessages, fetchMessages } from "../modules/language";
export const MyCoreApplication = ({ app, cookieInfo }) => {
const dispatch = useDispatch();
const config = useSelector(getConfigStore);
const configLoaded = useSelector(fetchConfigEnded);
const mobileMode = useSelector(isMobileMode);
const messages = useSelector(getMessages);
const locale = useSelector(getLocale);
const actions = {
getConfig: () => dispatch(getConfig()),
setLocale: (locale) => dispatch(setLocale(locale)),
fetchMessages: (locale) => dispatch(fetchMessages(locale)),
setMobileMode: (checkMobile) => dispatch(setMobileMode(checkMobile)),
};
if (config === null && !configLoaded) dispatch(getConfig());
else {
if (!locale && config) actions.setLocale(config.defaultLanguage);
}
return config ? (
<IntlProvider messages={messages} locale={locale} defaultLocale={config.defaultLanguage}>
<Notification />
<Router>{app}</Router>
{cookieInfo && cookieInfo.useCookie && cookieInfo.infoLink && <CookieBar infoLink={cookieInfo.infoLink} />}
</IntlProvider>
) : configLoaded ? (
<ErrorPage />
) : (
<LoadingSpinner />
);
};
The goal of my package is to build a library which create redux store receiving sagas and reducer from the custom application. In this mode a developer who use this library hasn't to create the store because module has already done.
In this project I use webpack and after run build and pack npm commands I've got a .tgz file that I use in a create-react-app project as a dependency. In this create-react-app project I use my package in the following mode:
import React from "react-dom";
import ReactDOM from "react-dom";
import { MyCore } from "my_core";
import { appSagas } from "./store/appSagas";
import { appReducers } from "./store/appReducers";
import { App } from "./container/App";
import "./styles/index.scss";
const wrapper = document.getElementById("container");
wrapper &&
ReactDOM.render(
<MyCore
withLogs={true}
applicationSagas={appSagas}
applicationReducers={appReducers}
app={<App />}
/>,
wrapper
);
And this is the App code:
import React from "react";
import { Layout } from "antd";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { MyHeader as Header } from "../components/MyHeader.jsx";
import { Components } from "my_core";
const { MyFooter: Footer } = Components;
const { Content } = Layout;
export const App = () => (
<Layout>
<Router>
<Header />
<Content>
<Switch>
<Route exact path="/">
hello
</Route>
</Switch>
<Footer />
</Content>
</Router>
</Layout>
);
Finally, inside MyHeader I use useSelector as the following code shows:
import React from "react";
import { useSelector } from "react-redux";
import { Utility } from "my_core";
const { configUtils } = Utility;
export const MyHeader = () => {
const mobileMode = useSelector(configUtils.isMobileMode);
return mobileMode ? <div>Mobile Header</div> : <div>Desktop Header</div>;
};
When I start the create-react-app project I encounter this error:
useSelector() Error: Could not find react-redux context value; please ensure the component is wrapped in a <Provider>
The same identical code, if written inside MyCore package project, works fine.
How can I solve this problem?
At this link github.com/iBobo5/myCore.git you can find myCore project. It's enough to run npm install and npm run export to obtain .tgz file. Once it has been created copy in a create-react-app "test" project and install it with react and react-dom dependencies. Other dependencies are installed by the library. Inside "test" project try to replace the import as shown above and inside a component use useSelector or useDispatch. In this way you could be able to reproduce my issue
The problem is probably that you have react-redux as a dependency rather than a peerDependency in your package.json. So you will potentially have two versions in the application in which the library is consumed, which causes the bug you described.
I am creating a blogging application using React with Server Side Rendering functionality. I create the application using Create React App.
I encounter an issue where my data coming from the server is rendered for a second then gone after react takes over the rendering process. I am using React Router Dom to pass the data from the server to the client react. Basically I am following this tutorial to create the application https://www.youtube.com/watch?v=NwyQONeqRXA but the video is lacking some information like getting the data on the API. So I reference this repository for getting the data on the API https://github.com/tylermcginnis/rrssr
Base on resources I gathered I ended up the following codes.
server.js
import express from "express";
import fs from "fs";
import path from "path";
import { StaticRouter, matchPath } from "react-router-dom";
import React from "react";
import ReactDOMServer from "react-dom/server";
import serialize from "serialize-javascript";
import App from "../src/App";
import routes from "../src/routes";
const app = express();
const PORT = 3001;
app.use(express.static(path.resolve(__dirname, "..", "build")));
app.get("*", (req, res, next) => {
// point to the html file created by CRA's build tool
const filePath = path.resolve(__dirname, "..", "build", "index.html");
fs.readFile(
path.resolve(filePath),
"utf-8",
(err, html_data) => {
if (err) {
console.error(err);
return res.status(500).send(`Some error happened: ${err}`);
}
const activeRoute =
routes.find(route => matchPath(req.url, route)) || {};
const promise = activeRoute.fetchInitialData
? activeRoute.fetchInitialData(req.path)
: Promise.resolve();
promise
.then(rawData => {
console.log('rawData', rawData[0]);
const context = { posts: rawData };
const markup = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
);
return res
.status(200)
.send(
html_data
.replace(
'<div id="root" class="container-fluid"></div>',
`<div id="root" class="container-fluid">${markup}</div>`
)
.replace(
"__INITIAL_DATA__={}",
`__INITIAL_DATA__=${serialize(rawData)}`
)
);
})
.catch(next);
}
);
});
app.listen(PORT, () => {
console.log(`App launched at http://localhost:${PORT}`);
});
Node JS Server entry point index.js
require("ignore-styles");
require("#babel/register")({
ignore: [/(node_modules)/],
presets: ["#babel/preset-env", "#babel/preset-react"]
});
require("./server");
Client react index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.css";
import "./index.css";
import "./fonts/VarelaRound-Regular.ttf";
ReactDOM.hydrate(
<BrowserRouter>
<App post_data={window.__INITIAL_DATA__} />
</BrowserRouter>,
document.getElementById("root")
);
Clieant react App.js
import React, { Component } from "react";
import "./App.css";
import { Route, Link, Redirect, Switch } from "react-router-dom";
import routes from "./routes";
class App extends Component {
render() {
return (
<div>
<Switch>
{routes.map(
({ path, exact, component: Component, ...rest }) => (
<Route
key={path}
path={path}
exact={exact}
render={props => (
<Component {...props} {...rest} />
)}
/>
)
)}
</Switch>
</div>
);
}
}
export default App;
When I am trying to output the data on the component it was gone and now staticContext pass from the server is undefined. What seems to be the issue here? Am I missing some configuration or library?
import React from "react";
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: this.props.staticContext
? this.props.staticContext.posts
: []
};
console.log("constructor", this.props); // STATIC CONTEXT UNDEFINED ON THIS OUTPUT
}
componentDidMount() {
console.log("componentDidMount", this.props);// STATIC CONTEXT UNDEFINED ON THIS OUTPUT
}
}