Hey this is my code and I want to print the networkType but it is not priniting out anything this code was working in App.js but not in home.js.
I created a class component in home.js
Home.js:
import {Component, React} from 'react';
import { BrowserRouter as Router, Link } from 'react-router-dom';
import Web3 from 'web3';
class Home extends Component
{
state={
person : [
{networkType:'None'}
]
}
componentDidMount()
{
this.loadBlockchainData();
}
async loadBlockchainData()
{
const web3 = new Web3(Web3.givenProvider || "https://localhost:8545");
const network = await web3.eth.net.getNetworkType();
this.setState(
{
person:[
{networkType:network}
]
}
)
}
render()
{
return(
<div>
<h1>Hello</h1>
<h1>Network is: {this.state.networkType}</h1>
</div>
)
}
}
export default Home;
Just update like this:
this.state.person[0].networkType
Related
I have a problem to access this.context in a class based consumer component. I have the following situation:
AppContext.js:
import React from "react";
const ContactContext = React.createContext(); // Create our context
export default ContactContext;
DataProvider.js:
import React, { Fragment } from "react";
import AppContext from "./AppContext";
export default class DataProvider extends React.Component {
state = {
contacts: {
contact1: {
id: 1,
firstName: 'Test User FN',
lastName: 'Test User LN'
}
}
};
render() {
return (
<>
<AppContext.Provider value={{contacts: this.state.contacts}}>
{this.props.children}
</AppContext.Provider>
</>
);
}
}
App.js:
import React from 'react';
import DataProvider from "./DataProvider";
import Contact from './components/contact/contact.component';
export default class App extends React.Component {
render() {
return (
<div>
<div className="container">
<DataProvider>
<Contact contactIndex={0}/>
</DataProvider>
</div>
</div>
);
}
}
The consumer Contact.js:
import React, { Component } from "react";
import AppContext from '../context/AppContext'
export default class Contact extends Component {
static contextType = AppContext;
componentDidMount () {
console.log('My context is: ' + this.context);
}
render() {
return (
<div className="card"></div>
);
}
}
The console output is:
My context is: undefined
Thanks for any help
Regards
Dakir
Only difference I see in the other answer's CodeSandbox is the import path is different.
import AppContext from "./AppContext";
vs:
import AppContext from '../context/AppContext'
Maybe OP has a filepath/import error?
p.s. If this is the error, TypeScript is a lifesaver for avoiding these kind of things in JS.
Your code seems right to me, I tried to replicate it in a Sandbox to find out the error and somehow works like a charm.
https://codesandbox.io/s/interesting-https-emgoz?file=/src/App.js
Tried to spot the difference but I couldn't honestly.
I'm having a problem while running my react js project.
componentDidMount not working.
my react.js version is ^16.13.1.
My code:
import React, { Component } from "react";
import "../../Assets/Styles/common.css";
import "./settingView.css";
import Sidebar from "../../Components/Sidebar/sidebar";
import Navbar from "../../Components/Navbar/navbar";
import Setting from "../../Components/Setting/setting";
import { getERPData } from '../../LocalStorage/localSrorage';
import history from '../../Routing/history';
class SettingView extends Component {
componentDidMount(){
console.log("Setting");
if(!getERPData()){
history.push("/");
console.log("Data not Found");
}
else{
console.log("Data Found");
}
}
render() {
return (
<React.Fragment>
</React.Fragment>
);
}
}
export default SettingView;
Here is the whole code for my component.
componentDidMount not working.
Ciao, if you are using React 16.13.1 you could use Hooks:
export default function SettingView {
useEffect(() => {
console.log("Setting");
if(!getERPData()){
history.push("/");
console.log("Data not Found");
}
else{
console.log("Data Found");
}
, []);
return (
<React.Fragment>
</React.Fragment>
);
}
By the way. I got solution for the whole problem. I just restricted the JSX on conditional rendering of local storage. and it worked.
import React, { Component } from "react";
import "../../Assets/Styles/common.css";
import "./settingView.css";
import Sidebar from "../../Components/Sidebar/sidebar";
import Navbar from "../../Components/Navbar/navbar";
import Setting from "../../Components/Setting/setting";
import { getERPData } from '../../LocalStorage/localSrorage';
import history from '../../Routing/history';
class SettingsPage extends Component {
state = { }
componentDidMount(){
if(!getERPData()){
history.push("/");
}
}
render() {
return (
<React.Fragment>
{
getERPData()?
<div className="w-100">
All My JSX here
</div>
:""
}
</React.Fragment>
)
}
}
export default SettingsPage;
this is how all the things got fine
I wonder how to use Inject without decorator.
First, I made this as Store.
//Data/imagedb
import { decorate, observable } from 'mobx';
class imageStore {
list = {
keyword : 'yoyo',
}
}
decorate(imageStore, {
list: observable,
})
export default imageStore;
Second, I made this code to inject Store on it.
//components/Image
import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
class Image extends Component {
render() {
const onPut2 = {onPut};
return (
<div>
{onPut2}
</div>
);
}
}
export default inject(({ imSt }) => ({
onPut: imSt.list.keyword,
}))(observer(Image));
And finally, this is my last code.
The error is "Onput is not defined" in second code.
import React from 'react';
import Image from 'components/Image';
import { Provider } from 'mobx-react';
import imageStore from 'Data/imagedb'
const imSt = new imageStore();
const Home = () => {
return (
<div>
<Provider imSt={imSt}>
<Image />
</Provider>
</div>
);
};
export default Home;
I'm trying to learn React and I'm struggling to redirect to the page where it shows the details about the clicked item. I have added the react-router-dom but I don't know where to go from here.
My brewery.js
import React from "react";
class Brewery extends React.Component {
render() {
const name = `${this.props.brewery.name} - ${this.props.brewery.city}`;
return <div>{name}</div>
}
}
export default Brewery;
My app.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Brewery from './components/brewery'
class App extends Component {
constructor(props) {
super(props);
this.state = {
breweries: []
};
}
componentDidMount() {
fetch("https://api.openbrewerydb.org/breweries")
.then(response => response.json())
.then((data) => {
this.setState({
breweries: data,
})
})
}
render() {
return(
<div>
{this.state.breweries.map((brewery) => {
return <Brewery key={brewery.name} brewery={brewery}/>
})}
</div>
)
}
}
export default App;
Start with below:
import { BrowserRouter,Route,Switch } from 'react-router-dom';
Now wrap you app.js in index.js with BrowserRouter like:
<BrowserRouter><App /></BrowserRouter>
You have router in you project. now define routes
<Switch><Route path="/" component={Home}/></Switch>
So whenever you type "/" Home component will load.
If you want to move to new page use props.history.push('/profile');. This will redirect you to profile page.
I do have this code and I'm going to use Cookies for first time but I get error below , anyone who can help me to fix the problem ?
"ERROR I FACE : Attempted import error: 'react-cookie' does not contain a default export (imported as 'Cookie'). "
import React from 'react';
import ReactDom from 'react-dom';
import './App.css';
import CountDown from './CountDown';
import Basket from './Basket';
import Cookie from 'react-cookie'
class Products extends React.Component{
constructor(props){
super(props);
this.state={
order : []
}
this.shop = this.shop.bind(this);
}
prevstate = [];
`enter code here`shop(evt){
this.prevstate.push(evt.target.id);
this.setState({
order : this.prevstate
})
console.log(Cookie.get('selected'))
Cookie.set('selected' , this.props.cart , {path :' /'});
}
render(){
return(
<div className="prowrap">
{this.props.prolist.map((name) => (
<div className="pro" key={name.id} style={{border:"1px red
solid"}} >
<img src={name.image}/>
<p>{name.name}</p>
<p>{name.detail}</p>
<p className="countdown"><CountDown time={name.date}/></p>
<div className="price">{name.price} Euro</div>
<button className="shop" id={name.id} onClick={this.shop}>Add To
Cart</button>
</div>))}
<Basket cart={this.state.order} allpro={this.props.prolist}/>
</div>
)
}
}
export default Products;
The error is clear react-cookie doesn’t have default export so you cannot import it like
import Cookie from 'react-cookie';
You need to import it like below
import { Cookies } from 'react-cookie';
Also it's not Cookie but Cookies. You are importing it wrongly
When it is default export then you don’t use {} to import but if it is not default export then you use {} to import it.
You need to import like import { withCookies, Cookies } from 'react-cookie'; and then cookies.get('selected'), refer the code below
Read the package readme carefully.
// App.jsx
import React, { Component } from 'react';
import { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';
import NameForm from './NameForm';
class App extends Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
};
constructor(props) {
super(props);
const { cookies } = props;
this.state = {
name: cookies.get('name') || 'Ben'
};
}
handleNameChange(name) {
const { cookies } = this.props;
cookies.set('name', name, { path: '/' });
this.setState({ name });
}
render() {
const { name } = this.state;
return (
<div>
<NameForm name={name} onChange={this.handleNameChange.bind(this)} />
{this.state.name && <h1>Hello {this.state.name}!</h1>}
</div>
);
}
}
export default withCookies(App);