Blank screen after using react <Provider> - javascript

I am trying to make a webpage using React js and use redux template. I am trying to wrap my component around < Provider >. After wrapping i get a blank page. I tried using React developer tools that too appears blank. here is my code. I have tried different methods nut none of them works.
Main.js
import Title from './Title'
import Photowall from './Photowall'
import AddPhoto from './AddPhoto'
import { Route } from 'react-router-dom'
class Main extends Component{
constructor(){
super()
this.state= {
posts : [{
id: "0",
description: "beautiful landscape",
imageLink: "https://image.jimcdn.com/app/cms/image/transf/none/path/sa6549607c78f5c11/image/i4eeacaa2dbf12d6d/version/1490299332/most-beautiful-landscapes-in-europe-lofoten-european-best-destinations-copyright-iakov-kalinin.jpg" +
"3919321_1443393332_n.jpg"
}, {
id: "1",
description: "Aliens???",
imageLink: "https://s3.india.com/wp-content/uploads/2017/12/rocket.jpg"
}, {
id: "2",
description: "On a vacation!",
imageLink: "https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/08/24/104670887-VacationExplainsTHUMBWEB.1910x1000.jpg"
}],
}
this.removePhoto=this.removePhoto.bind(this)
}
removePhoto(postRemoved){
console.log(postRemoved.description)
this.setState((state) => ({
posts: state.posts.filter(post => post !== postRemoved)
}))
}
addPhoto(postSubmitted){
this.setState(state => ({
posts:state.posts.concat([postSubmitted])
}))
}
componentDidMount(){
}
componentDidUpdate(prevProps,prevState){
console.log(prevState.posts)
console.log(this.state)
}
render() {
return (
<div>
<Route exact path="/" render={() => (
<div>
<Title title={'Photowall'}/>
<Photowall posts={this.state.posts} onRemovePhoto={this.removePhoto} onNavigate={this.navigate}/>
</div>
)}/>
<Route path="/AddPhoto" render={({history})=>(
<AddPhoto onAddPhoto={(addedPost)=>{
this.addPhoto(addedPost)
history.push('/')
}}/>
)}/>
</div>
)
}
}
export default Main
AddPhoto.js
import React, { Component } from "react"
class AddPhoto extends Component{
constructor(){
super()
this.handleSubmit=this.handleSubmit.bind(this)
}
handleSubmit(event){
event.preventDefault();
const imageLink = event.target.elements.link.value
const description = event.target.elements.description.value
const post = {
id:0,
description:description,
imageLink:imageLink
}
if(description && imageLink){
this.props.onAddPhoto(post)
}
}
render(){
return(
<div>
<h1>Photowall</h1>
<div className="form">
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="Link" name="link"/>
<input type="text" placeholder="Description" name="description"/>
<button>Post</button>
</form>
</div>
</div>
)
}
}
export default AddPhoto
Photo.js
import React, {Component} from "react";
import PropTypes from 'prop-types'
function Photo(props){
const post =props.post
return <figure className="figure">
<img className="photo" src={post.imageLink} alt={post.description}/>
<figcaption><p>{post.description}</p></figcaption>
<div className="button-container">
<button className="remove-button" onClick={()=>{
props.onRemovePhoto(post);
}}> Remove </button>
</div>
</figure>
}
Photo.propTypes={
post: PropTypes.object.isRequired,
onRemovePhoto:PropTypes.func.isRequired
}
export default Photo
Photowall.js
import React,{ Component} from 'react'
import Photo from './Photo'
import PropTypes from 'prop-types'
import {Link} from 'react-router-dom'
function Photowall(props){
return <div>
<Link className='addIcon' to='/AddPhoto' ><img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTIgMGMtNi42MjcgMC0xMiA1LjM3My0xMiAxMnM1LjM3MyAxMiAxMiAxMiAxMi01LjM3MyAxMi0xMi01LjM3My0xMi0xMi0xMnptNyAxNGgtNXY1aC00di01aC01di00aDV2LTVoNHY1aDV2NHoiLz48L3N2Zz4="></img> </Link>
{/*<button onClick={props.onNavigate} className='addIcon'> + </button>*/}
<div className='photo-grid'>
{props.posts.map((post, index) => <Photo key={index} post={post} onRemovePhoto={props.onRemovePhoto}/>)}
</div>
</div>
}
Photowall.propTypes={
posts: PropTypes.array.isRequired,
onRemovePhoto:PropTypes.func.isRequired
}
export default Photowall
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Main from './Components/Main'
import './styles/stylesheet.css'
import {BrowserRouter} from 'react-router-dom'
import {createStore} from 'redux'
import rootReducer from './redux/reducer'
import {Provider} from "react-redux";
const store = createStore(rootReducer)
ReactDOM.render(<Provider store={store}><BrowserRouter><Main/></BrowserRouter></Provider>, document.getElementById('root'));
reducer.js
import posts from '../data/posts'
const postReducer = function posts(state = posts,action){
return state
}
export default postReducer

Related

Provider tag in react causing blank screen

I am trying to make a webpage using React js and use redux template. I am trying to wrap my component around < Provider >. After wrapping i get a blank page. I tried using React developer tools that too appears blank. here is my code.Here is the error i am getting
Uncaught Error: Expected the reducer to be a function.
at createStore (createStore.js:55:1)
at ./src/index.js (index.js:9:1)
at options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:24:1)
at startup:7:1
at startup:7:1
Main.js
import Title from './Title'
import Photowall from './Photowall'
import AddPhoto from './AddPhoto'
import { Route } from 'react-router-dom'
class Main extends Component{
constructor(){
super()
this.state= {
posts : [{
id: "0",
description: "beautiful landscape",
imageLink: "https://image.jimcdn.com/app/cms/image/transf/none/path/sa6549607c78f5c11/image/i4eeacaa2dbf12d6d/version/1490299332/most-beautiful-landscapes-in-europe-lofoten-european-best-destinations-copyright-iakov-kalinin.jpg" +
"3919321_1443393332_n.jpg"
}, {
id: "1",
description: "Aliens???",
imageLink: "https://s3.india.com/wp-content/uploads/2017/12/rocket.jpg"
}, {
id: "2",
description: "On a vacation!",
imageLink: "https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/08/24/104670887-VacationExplainsTHUMBWEB.1910x1000.jpg"
}],
}
this.removePhoto=this.removePhoto.bind(this)
}
removePhoto(postRemoved){
console.log(postRemoved.description)
this.setState((state) => ({
posts: state.posts.filter(post => post !== postRemoved)
}))
}
addPhoto(postSubmitted){
this.setState(state => ({
posts:state.posts.concat([postSubmitted])
}))
}
componentDidMount(){
}
componentDidUpdate(prevProps,prevState){
console.log(prevState.posts)
console.log(this.state)
}
render() {
return (
<div>
<Route exact path="/" render={() => (
<div>
<Title title={'Photowall'}/>
<Photowall posts={this.state.posts} onRemovePhoto={this.removePhoto} onNavigate={this.navigate}/>
</div>
)}/>
<Route path="/AddPhoto" render={({history})=>(
<AddPhoto onAddPhoto={(addedPost)=>{
this.addPhoto(addedPost)
history.push('/')
}}/>
)}/>
</div>
)
}
}
export default Main
AddPhoto.js
import React, { Component } from "react"
class AddPhoto extends Component{
constructor(){
super()
this.handleSubmit=this.handleSubmit.bind(this)
}
handleSubmit(event){
event.preventDefault();
const imageLink = event.target.elements.link.value
const description = event.target.elements.description.value
const post = {
id:0,
description:description,
imageLink:imageLink
}
if(description && imageLink){
this.props.onAddPhoto(post)
}
}
render(){
return(
<div>
<h1>Photowall</h1>
<div className="form">
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="Link" name="link"/>
<input type="text" placeholder="Description" name="description"/>
<button>Post</button>
</form>
</div>
</div>
)
}
}
export default AddPhoto
Photo.js
import React, {Component} from "react";
import PropTypes from 'prop-types'
function Photo(props){
const post =props.post
return <figure className="figure">
<img className="photo" src={post.imageLink} alt={post.description}/>
<figcaption><p>{post.description}</p></figcaption>
<div className="button-container">
<button className="remove-button" onClick={()=>{
props.onRemovePhoto(post);
}}> Remove </button>
</div>
</figure>
}
Photo.propTypes={
post: PropTypes.object.isRequired,
onRemovePhoto:PropTypes.func.isRequired
}
export default Photo
Photowall.js
import React,{ Component} from 'react'
import Photo from './Photo'
import PropTypes from 'prop-types'
import {Link} from 'react-router-dom'
function Photowall(props){
return <div>
<Link className='addIcon' to='/AddPhoto' ><img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTIgMGMtNi42MjcgMC0xMiA1LjM3My0xMiAxMnM1LjM3MyAxMiAxMiAxMiAxMi01LjM3MyAxMi0xMi01LjM3My0xMi0xMi0xMnptNyAxNGgtNXY1aC00di01aC01di00aDV2LTVoNHY1aDV2NHoiLz48L3N2Zz4="></img> </Link>
{/*<button onClick={props.onNavigate} className='addIcon'> + </button>*/}
<div className='photo-grid'>
{props.posts.map((post, index) => <Photo key={index} post={post} onRemovePhoto={props.onRemovePhoto}/>)}
</div>
</div>
}
Photowall.propTypes={
posts: PropTypes.array.isRequired,
onRemovePhoto:PropTypes.func.isRequired
}
export default Photowall
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Main from './Components/Main'
import './styles/stylesheet.css'
import {BrowserRouter} from 'react-router-dom'
import {createStore} from 'redux'
import rootReducer from './redux/reducer'
import {Provider} from "react-redux";
const store = createStore(rootReducer)
ReactDOM.render(<Provider store={store}><BrowserRouter><Main/></BrowserRouter></Provider>, document.getElementById('root'));
reducer.js
import posts from '../data/posts'
const postReducer = function posts(state = posts,action){
return state
}
export default postReducer

Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>

Please I'm new to react. I'm trying to render data from my backend using react axios and hooks. I keep on getting this error message and I ensured the App was wrapped in a provider. Do I have to wrap the Homescreen component in a provider before exporting it? Thanks.
This is the Homescreen.js ; To display the data
import React, { useEffect} from 'react';
import {Link} from 'react-router-dom'
import { useSelector } from 'react-redux/lib/hooks/useSelector';
import { useDispatch } from 'react-redux/lib/hooks/useDispatch';
import { listProducts } from '../actions/productActions';
import {Provider }from 'react-redux';
function HomeScreen (props) {
const productList = useSelector(state => state.productList);
const { products, loading, error} = productList;
const dispatch = useDispatch();
useEffect(()=>{
dispatch(listProducts());
return ()=> {
//
};
}, [ dispatch ])
return loading? <div> loading... </div>:
error? <div> {error} </div>:
(
<ul className="products">
{
products.map(product =>
<li key = {product._id} >
<div className="product">
<Link to= {'/product/'+ product._id}>
<img src={product.image} className="product-image" alt="product"></img>
</Link>
<div className="product-name">
<Link to= {'/product/'+ product._id}> {product.name} </Link>
</div>
<div className="product-brand"> {product.brand}</div>
<div className="product-price"> ${product.price}</div>
<div className="rating"> {product.price} Stars ({product.numReviews} Reviews)</div>
</div>
</li>
)
}
</ul>
)
}
export default HomeScreen;
This is the App;
import React from 'react';
import {Link, BrowserRouter ,Route } from 'react-router-dom'
import './App.css';
import HomeScreen from './screens/HomeScreen'
import ProductScreen from './screens/ProductScreen'
import {Provider }from 'react-redux';
function App() {
const openMenu = ()=>{
document.querySelector(".sidebar").classList.add("open")
}
const closeMenu = ()=>{
document.querySelector(".sidebar").classList.remove("open")
}
return (
<BrowserRouter>
<div className="grid-container">
<header className="header">
<div className="brand">
<button onClick={openMenu}>
☰
</button>
<Link to = "/">Amazone</Link>
</div>
<div className="header-links">
Cart
SigniN
</div>
</header>
<aside className="sidebar">
<h3> Shopping Categories</h3>
<button className="sidebar-close-button" onClick={closeMenu}>X </button>
<li>
Pants
</li>
<li>
Shirts
</li>
</aside>
<main className="main">
<div className="content">
<Route path="/product/:id" component = {ProductScreen} />
<Route path="/" exact = {true} component = {HomeScreen} />
</div>
</main>
<footer className="footer">
All Rights Reserved
</footer>
</div>
</BrowserRouter>
);
}
export default App;
This is the Index.js
import React from 'react';
import {Provider }from 'react-redux';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import allreducer from './allreducer.js'
import thunk from 'redux-thunk';
import {createStore, applyMiddleware, compose} from 'redux';
// to see the action dispatched in the state at the browser
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const initialState = {};
//Thunk is a middleware that allows operation of async in the action
const store = createStore(allreducer, initialState, composeEnhancer(applyMiddleware(thunk)));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
,
document.getElementById('root')
);
serviceWorker.unregister();
The Reducer:
import { PRODUCT_LIST_REQUEST, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_FAIL, PRODUCT_DETAILS_REQUEST, PRODUCT_DETAILS_SUCCESS, PRODUCT_DETAILS_FAIL } from "../constants/productConstants";
//Reducers
function productListReducer (state = {product: []}, action){
switch(action.type){
case PRODUCT_LIST_REQUEST:
return {loading: true};
case PRODUCT_LIST_SUCCESS:
return {loading: false, products: action.payload}
case PRODUCT_LIST_FAIL:
return {loading:false, error: action.payload}
default:
return state;
}
}
Reducer Constants;
export const PRODUCT_LIST_REQUEST = 'PRODUCT_LIST_REQUEST';
export const PRODUCT_LIST_SUCCESS = 'PRODUCT_LIST_SUCCESS';
export const PRODUCT_LIST_FAIL = 'PRODUCT_LIST_FAIL';
export const PRODUCT_DETAILS_REQUEST = 'PRODUCT_DETAILS_REQUEST';
export const PRODUCT_DETAILS_SUCCESS = 'PRODUCT_DETAILS_SUCCESS';
export const PRODUCT_DETAILS_FAIL = 'PRODUCT_DETAILS_FAIL';
Reducer Action;
import { PRODUCT_LIST_REQUEST, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_FAIL, PRODUCT_DETAILS_REQUEST, PRODUCT_DETAILS_SUCCESS, PRODUCT_DETAILS_FAIL } from "../constants/productConstants";
//Reducers
function productListReducer (state = {product: []}, action){
switch(action.type){
case PRODUCT_LIST_REQUEST:
return {loading: true};
case PRODUCT_LIST_SUCCESS:
return {loading: false, products: action.payload}
case PRODUCT_LIST_FAIL:
return {loading:false, error: action.payload}
default:
return state;
}
}
The issue is that you're importing your hooks from 'react-redux/lib/hooks/useSelector' instead of 'react-redux'.
Instead of:
import { useSelector } from 'react-redux/lib/hooks/useSelector';
import { useDispatch } from 'react-redux/lib/hooks/useDispatch';
use:
import { useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';

React router: component not rendering after login

I'm building a website using React and I'm trying to redirect the user to the index page after the login, but my component is not rendering anything, although I'm being redirected and I can see the URL changing from /welcome#/login to /main.
Since I'm not getting any error messages and the webpack is being successfully compiled, I can't see what's wrong anymore.
Any ideas of what could possibly be wrong?
Thank you very much!
Start.js
import React from "react";
import ReactDOM from "react-dom";
import Welcome from "./welcome";
import { App } from "./app";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import reduxPromise from "redux-promise";
import { composeWithDevTools } from "redux-devtools-extension";
import reducer from "./reducer";
const store = createStore(
reducer,
composeWithDevTools(applyMiddleware(reduxPromise))
);
let element;
if (location.pathname === "/welcome") {
element = <Welcome />;
} else {
init(store);
element = (
<Provider store={store}>
<App />
</Provider>
);
}
ReactDOM.render(element, document.querySelector("main"));
Welcome.js
import React from "react";
import Register from "./register";
import Login from "./login";
import { HashRouter, Route, Redirect } from "react-router-dom";
export default class Welcome extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<HashRouter>
<div className="register-wrapper">
<div>
<Route path="/login" component={Login} />
<Route exact path="/" component={Register} />
</div>
</div>
</HashRouter>
);
}
}
Login Component
import React from "react";
import axios from "./axios";
export default class Login extends React.Component {
constructor(props) {
super(props);
this.state = { error: false };
this.loginButton = this.loginButton.bind(this);
this.handleChange = this.handleChange.bind(this);
}
loginButton(e) {
e.preventDefault();
axios
.post("/login", this.state)
.then(res => {
if (res.data.success) {
location.replace("/main");
} else {
this.setState({
error: true
});
}
})
.catch(error => console.log(error));
}
handleChange(e) {
this.setState(
{
[e.target.name]: e.target.value
},
() => console.log("this.state:", this.state)
);
}
render() {
return (
<div className="login-main-container">
{this.state.error && <h2>Ops! Something went wrong.</h2>}
<h1 className="login-title">Kathi & Rodolfo</h1>
<h2 className="login-subtitle">Dear guest, please login first</h2>
<div className="login-container">
<form className="login-form">
<label className="label-login" htmlFor="email"> username </label>
<input className="input-login"
name="email"
placeholder="Best Couple You Know"
onChange={this.handleChange}
/>
<label className="label-login" htmlFor="password"> password </label>
<input className="input-login"
name="password"
type="password"
placeholder="Super Loving Password"
onChange={this.handleChange}
/>
<button
className="login-button"
onClick={this.loginButton}
>
Login
</button>
</form>
</div>
<h4 className="login-info">Information about username and password can be found on the Save The Date card</h4>
</div>
);
}
}
Index Component (Main)
import React from "react";
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state ={ error: false};
}
render () {
return (
<div className="main-container">
<header>
<p>the wedding</p>
<p>rpsv</p>
<p>contact us</p>
<p>wedding gift</p>
</header>
{this.state.error && <h2>Ops! Something went wrong.</h2>}
<div className="save-the-date-img">
<h1>Save The Date</h1>
</div>
</div>
);
}
}
App.js
import React from "react";
import { BrowserRouter, Route, Link } from "react-router-dom";
import Main from "./main";
export class App extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<BrowserRouter>
<div>
<Route exact path="/main" Component={Main}/>
</div>
</BrowserRouter>
);
}
}
location.replace("/main");
I think this line is wrong in your code.
While you are using React, you'd rather use react-router-dom's functionality than browser built-in feature.
Change the line to this.props.history.push('/main')
Give your file structure. Your component Login is not in BrowserRouter, but must be. Check the official sample: https://reacttraining.com/react-router/web/guides/quick-start.
instead of
location.replace("/main");
use
history.push("/main")

How can I maintain my store's state while using react-router and redux?

I am building an app prototype that essentially simulates ecommerce. I have components that each have different items that can be added to a cart(below I just show an example of how one would basically work). These components are accessed via different routes using the react-router. There is a header component that displays the number of items currently in the cart. The header gets the number of items in the cart from the state in the redux store. However, if I navigate to a new route, the store goes back to the default state. I need the the store to keep its state when a new route is navigated to. For example, if I go to the ShoppingPage, add an item to the cart, and then go back to the Home page, I need the cart to still have an item in it.
actions.js
export const actionTypes = Object.freeze({
UPDATE_CART: Symbol('UPDATE_CART'),
});
export const updateCart = (payload) => {
return {
type: actionTypes.UPDATE_CART,
payload,
};
};
export default actionTypes;
reducer.js
import actions from './actions';
export const INITIAL_STATE = {
cart: [],
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case actions.UPDATE_CART: {
return {
...state,
cart: action.payload,
};
}
default: {
return state;
}
};
};
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer, { INITIAL_STATE } from './reducer';
const store = createStore(reducer, INITIAL_STATE);
console.log(store.getState());
ReactDOM.render(
<Provider store ={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
, document.getElementById('root'));
serviceWorker.unregister();
ShoppingPage.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { updateCart } from './actions';
class ShoppingPage extends Component {
addToCart = () => {
const cart = [...this.props.cart];
cart.push('new item');
this.props.modifyCart(cart);
render() {
return(
<div>
<button onClick={addToCart}>
Add To Cart
</button>
</div>
)
}
}
const mapDispatchToProps = dispatch => ({
modifyCart: payload => dispatch(updateCart(payload)),
});
const mapStateToProps = state => ({
cart: state.cart,
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(ShoppingPage);
Home.js
import React, { Component } from 'react';
import { ListGroup, ListGroupItem } from 'reactstrap';
class Home extends Component {
render() {
return(
<div>
<ListGroup>
<ListGroupItem><a href='/ShoppingPage'>ShoppingPage</a></ListGroupItem>
</div>
)
}
}
export default Home;
Header.js
import React, { Component } from 'react';
import { Navbar, NavbarBrand } from 'reactstrap';
import { connect } from 'react-redux';
class Header extends Component {
render() {
return(
<Navbar sticky='top' className='nav'>
<NavbarBrand href='/'>Online Shopping</NavbarBrand>
<span>{'Items in Cart: '}{this.props.cart.length}</span>
</Navbar>
)
}
}
const mapStateToProps = state => ({
cart: state.cart,
});
export default connect(
mapStateToProps
)(Header);
Routes.js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from './Home';
import ShoppingPage from './ShoppingPage';
const Routes = () => (
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/ShoppingPage' component={ShoppingPage} />
</Switch>
);
export default Routes;
App.js
import React from 'react';
import Routes from './Routes';
import Header from './Header';
function App() {
return (
<div>
<Header />
<Routes />
</div>
);
}
export default App;
What's likely happening is that during navigation the web app "reloads" again (which is wiping the redux state). In order to navigate with react router you want to look at <Link>.
For example,
Home.js
<a href='/ShoppingPage'>ShoppingPage</a>
should be changed to:
<Link to="/ShoppingPage">ShoppingPage</Link>

Faced TypeError: render is not a function when using Context API

I am new to React ans was learning Context API and during the use of it I faced this error TypeError: render is not a function. I also found the this answer React Context: TypeError: render is not a function in the platform which is close to my problem but no result. Here is the code I am using:
import React, { Component } from "react";
import MyContext from "../../Containers/Context/Context";
class Track extends Component {
render() {
return (
<MyContext>
{value => {
return <div>{value.heading}</div>;
}}
</MyContext>
);
}
}
export default Track;
import React, { Component } from "react";
const Context = React.createContext();
export class MyContext extends Component {
state = { track_list: [], heading: "Top Ten Tracks" };
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
);
}
}
export default MyContext = Context.Consumer;
import React, { Component, Fragment } from "react";
import "./App.css";
import Header from "../src/Components/Header/Header";
import Search from "../src/Components/Search/Search";
import Tracks from "../src/Components/Tracks/Tracks";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import NotFound from "./Components/NotFound/NotFound";
import MyContext from "./Containers/Context/Context";
class App extends Component {
render() {
return (
<MyContext>
<Router>
<Fragment>
<Header />
<div className="container">
<Search />
<Switch>
<Route exact path="/" component={Tracks} />
<Route component={NotFound} />
</Switch>
</div>
</Fragment>
</Router>
</MyContext>
);
}
}
export default App;
Your export and import statements are problematic.
first you export class MyContext then you immediately overwrite MyContext with Context.Consumer.
Fix your export statements and then fix your imports. import the Context.Consumer in file Track, and import the Context.Provider in file App
Containers/Context/Context.js
import React, { Component } from "react";
const Context = React.createContext();
class MyContextProvider extends Component {
state = { track_list: [], heading: "Top Ten Tracks" };
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
);
}
}
const MyContextConsumer = Context.Consumer;
export {MyContextProvider,MyContextConsumer};
Track.js
import React, { Component } from "react";
import {MyContextConsumer} from "../../Containers/Context/Context";
class Track extends Component {
render() {
return (
<MyContextConsumer>
{value => {
return <div>{value.heading}</div>;
}}
</MyContextConsumer>
);
}
}
export default Track;
App.js
import React, { Component, Fragment } from "react";
import "./App.css";
import Header from "../src/Components/Header/Header";
import Search from "../src/Components/Search/Search";
import Tracks from "../src/Components/Tracks/Tracks";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import NotFound from "./Components/NotFound/NotFound";
import {MyContextProvider} from "./Containers/Context/Context";
class App extends Component {
render() {
return (
<MyContextProvider>
<Router>
<Fragment>
<Header />
<div className="container">
<Search />
<Switch>
<Route exact path="/" component={Tracks} />
<Route component={NotFound} />
</Switch>
</div>
</Fragment>
</Router>
</MyContextProvider>
);
}
}
export default App;

Categories

Resources