Component not loading when route changed - javascript

I am using Preact. I first tried preact-router then wouter for routing, but the problem still exists for one specific component. Here is the main entry where all routes defined:
import { h, Component } from 'preact';
import { Route } from "wouter-preact";
import Header from './partials/header';
import Home from './pages/home';
import News from './pages/news';
import Article from './pages/article';
export default class App extends Component {
render() {
return (
<div id="app">
<Header />
<Route path="/"><Home /> </Route> // working perfectly
<Route path="/a/:article"> <Article /> </Route> // not working
<Route path="/n/:newspaper"><News /> </Route> // working
</div>
);
}
}
and here is the simplified second component which is working perfectly :
import { h, Fragment } from 'preact';
import { Link, Route } from "wouter-preact";
import useFetch from '../../utils/ajax';
export default function News() {
const url = window.location.pathname.split('/');
const { data, loading } = useFetch(domain + '/api/v1/news/?newspaper=' + url[2]);
return (
<Fragment>
{loading ? (
// loading indicator
) : (
<main role="main">
<div className="py-5">
<div className="container">
<div className="row">
{data.results.map((nisha, index) => (
<div className="col-sm-6" key={index}>
<div className="col-md-10" >
<div className="card mb-2 shadow-lg" style={{ border: 'none' }} >
<Link href={'/a/' + nisha.slug}>
<img className="card-img-top" src={ nisha.cover_image } alt={ nisha.slug } />
</Link>
<div className="card-body">
// body
<div className="card-footer text-muted">
// footer
</div>
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</main>
)}
</Fragment>
);
}
and finally the problematic component, when I click any link from previous component, browser url changing but the component is not loading (there is no debug console message in browser console).
export default function Article() {
console.log("loaded");
return (
<div className="main">
<div className="py-5">
<div className="column">
<div>example article</div>
</div>
</div>
</div>
);
}

Related

How to pass props via Route in ReactJS

I have my Parent App.js file where I have two child components, Products, and Cart. I am trying to pass my cart property to child Cart.js but haven't been successful.
App.js
import React,{useState} from 'react';
import {
Route,
BrowserRouter as Router,
} from 'react-router-dom';
import Cart from './components/Cart';
import Product from './components/Product';
function App() {
const [cart, setCart]= useState([]);
const addToCart=(product)=>{
console.log("addToCart button clicked",product)
setCart([...cart, {...product}])
}
return (
<Router>
<Route path="/home/"
render ={()=> < Product addToCart={addToCart}/>}
/>
<Route path="/cart/"
render ={()=> < Cart cart={cart} />}
/>
<div className="App">
</div>
</Router>
);
}
export default App;
Cart.js
import React from 'react'
export default function Cart({cart}) {
return (
<div >
hello
<div className="products" >
{cart.map((product, idx)=>(
<div key={idx}>
<h3>{product.name}</h3>
<h4>{product.cost}</h4>
<img src={product.image} alt = {product.name} />
</div>
))}
</div>
<div>
</div>
</div>
)
}
Product.js
import React,{useState} from 'react';
export default function Product({addToCart}) {
const [products]=useState([
{
name: 'iPhone',
cost : '$899.99',
image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQB6BMWrPXA9KyTtxa6o600mjeUNJ7zSXgaNt--FDCR6YjQ4XWS5G1J3dSF5ChurfQEGxorkxYs&usqp=CAc',
},
{
name: 'Samsung',
cost : '$599.99',
image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQUGMCcF3_XBIKH5Dja-9iCkRP4CSA-CYaylQ&usqp=CAU'
}
])
return(
<div className="main-page">
<h1>Product Page </h1>
<div className="products" >
{products.map((product, idx)=>(
<div key={idx}>
<h3>{product.name}</h3>
<h4>{product.cost}</h4>
<img src={product.image} alt = {product.name} />
<button onClick={()=>addToCart(product)}
>Add to Cart</button>
</div>
))}
</div>
<div>
</div>
</div>
)
}
localhost:3000/ shows all the products but when I go to localhost:3000/cart/ I don't see my cart items. The mistake I am making I think is in the Route.
<Route path="/cart/"
render ={()=> < Cart cart={cart} />}
/>
How should I pass the cart variable from App.js to Cart.js ?

React JS - How does 2 separated components able to receive 1 same state?

I am a beginner in using the React JS framework. Based on the official React JS documentation, an example is given for changing the state of a component that has a connected hierarchy. But in my case this time I split the components for Header and Main separately.
index.js
ReactDOM.render(
<React.StrictMode>
<Header />
<Main />
</React.StrictMode>,
document.getElementById('root')
);
In the Header component I also have another sub component that functions to activate / deactivate the sidebar which is also a sub menu for the Main component.
Header.js
import { BtnSidebarOnClick } from './Sidebar';
const Header = () => {
return (
<header className="header">
<div className="header__logo">
<BtnSidebarOnClick />
<div className="header__logo_img">
<a className="link"
href="/">
<img src=""
alt="Schedule App" />
</a>
</div>
</div>
<nav className="header__nav">
...
</nav>
</header>
);
}
export default Header;
Main.js
import { Sidebar } from './Sidebar';
const Main = () => {
return (
<main className="main">
<Sidebar />
<div className="main__content">
...
</div>
</main>
);
}
export default Main;
Notice that the BtnSidebarOnClick and Sidebar components are not connected. In my case, this time I want to make the Sidebar component accept state to detect whether the button contained in the BtnSidebarOnClick component is clicked / not.
Sidebar.js
class BtnSidebarOnClick extends React.Component {
constructor(props) {
super(props);
this.state = { onClick: false };
}
handleClick() {
this.setState(state => ({ onClick: !state.onClick }));
}
render() {
return (
<div className="header__logo_btn">
<div className="button button--hover button--focus"
role="button"
tabIndex="0"
onClick={this.handleClick.bind(this)}>
<i className="material-icons">menu</i>
</div>
</div>
);
}
}
const Sidebar = () => {
return (
<div className="main__sidebar"> {/* set style if BtnSidebarOnClick clicked */}
<div className="main__sidebar_menu">
<div className="tag-link">
<a className="link link--hover link--focus link--active"
href="/">
<i className="material-icons">insert_drive_file</i>
<span className="link-title">Files</span>
</a>
</div>
</div>
</div>
);
}
export { Sidebar, BtnSidebarOnClick };
So how do you set these two components to receive the same state?
TLDR; You should pull out the button state into the parent and pass it into the children component.
By the way, it is a common way to have file App.js for your main Application file. In your case, it should be like this:
index.js
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
App.js
class App extends React.Component {
constructor(props) {
super(props);
this.state = { isClicked: false };
}
handleClick() {
this.setState(state => ({ isClicked: !state.isClicked }));
}
render() {
return (
<div>
<Header onClick={this.handleClick} /> // --> notice
<Main isClicked={this.state.isClicked} /> // --> notice
</div>
)
}
}
Header.js
import BtnSidebar from './BtnSidebar';
const Header = (props) => {
return (
<header className="header">
<div className="header__logo">
<BtnSidebar onClick={props.onClick} /> // --> notice
<div className="header__logo_img">
<a className="link"
href="/">
<img src=""
alt="Schedule App" />
</a>
</div>
</div>
<nav className="header__nav">
...
</nav>
</header>
);
}
Main.js
import Sidebar from './Sidebar';
const Main = (props) => {
return (
<main className="main">
<Sidebar isClicked={props.isClicked} /> // --> notice
<div className="main__content">
...
</div>
</main>
);
}
BtnSidebar.js
const BtnSidebar = (props) => {
return (
<div className="header__logo_btn">
<div className="button button--hover button--focus"
role="button"
tabIndex="0"
onClick={props.onClick} // --> notice
>
<i className="material-icons">menu</i>
</div>
</div>
);
}
Sidebar.js
const Sidebar = (props) => {
return (
<div
className={
props.isClicked ? 'main__sidebar-clicked' : 'main__sidebar' // --> notice
}
>
<div className="main__sidebar_menu">
<div className="tag-link">
<a className="link link--hover link--focus link--active"
href="/">
<i className="material-icons">insert_drive_file</i>
<span className="link-title">Files</span>
</a>
</div>
</div>
</div>
);
}

Cannot read property 'image' of undefined

I am trying to build an application using react but I got an error saying "cannot read property 'image' of undefined"
Please help me if you found any issue because I am new in this framework.
The error showing up
function RenderCard({ item }) {
5 | return (
6 | <Card>
> 7 | <CardImg src={item.image} alt={item.name} />
8 | <CardBody>
9 | <CardTitle>{item.name}</CardTitle>
10 | {item.designation ? <CardSubtitle>{item.designation}</CardSubtitle> : null}
Full Code
import React from "react";
import { Card, CardImg, CardText, CardBody, CardTitle, CardSubtitle } from "reactstrap";
function RenderCard({ item }) {
return (
<Card>
<CardImg src={item.image} alt={item.name} />
<CardBody>
<CardTitle>{item.name}</CardTitle>
{item.designation ? <CardSubtitle>{item.designation}</CardSubtitle> : null}
<CardText>{item.description}</CardText>
</CardBody>
</Card>
);
}
function Home(props) {
return (
<div className="container">
<div className="row align-items-start">
<div className="col-12 col-md m-1">
<RenderCard item={props.dish} />
</div>
<div className="col-12 col-md m-1">
<RenderCard item={props.promotion} />
</div>
<div className="col-12 col-md m-1">
<RenderCard item={props.leader} />
</div>
</div>
</div>
);
}
export default Home;
And I'm importing it from another file
From my understanding there must be issue in importing the file
import React, { Component } from "react";
import Home from "./HomeComponent";
import Contact from "./ContactComponent";
import Menu from "./MenuComponents";
import Dishdetail from "./DishdetailComponent";
import Header from "./HeaderComponent";
import Footer from "./FooterComponent";
import { Dishes } from "../shared/dishes";
import { Comments } from "../shared/comments";
import { Leaders } from "../shared/leaders";
import { Promotions } from "../shared/promotions";
import { Switch, Route, Redirect } from "react-router-dom";
class Main extends Component {
constructor(props, context) {
super(props, context);
this.state = {
dishes: Dishes,
comments: Comments,
promotions: Promotions,
leaders: Leaders,
};
}
render() {
const HomePage = () => {
return (
<Home
dish={this.state.dishes.filter((dish) => dish.featured)[0]}
promo={this.state.promotions.filter((promo) => promo.featured)[0]}
leader={this.state.leaders.filter((leader) => leader.featured)[0]}
/>
);
};
const DishWithId = ({ match }) => {
return (
<Dishdetail
dish={this.state.dishes.filter((dish) => dish.id === parseInt(match.params.dishId, 10))[0]}
comments={this.state.comments.filter((comment) => comment.dishId === parseInt(match.params.dishId, 10))[0]}
/>
);
};
return (
<div>
<Header />
<Switch>
<Route path="/home" component={HomePage} />
<Route exact path="/menu" component={() => <Menu dishes={this.state.dishes} />} />
<Route path="/menu/:dishId" component={DishWithId} />
<Route exact path="/contactus" component={Contact} />
<Redirect to="/home" />
</Switch>
<Footer />
</div>
);
}
}
export default Main;
Thanks
You pass a promo prop to Home component:
<Home promo={...} />
But in Home component, you use using props.promotion which is undefined when it should be props.promo:
// don't use props.promotion, use props.promo instead
<RenderCard item={props.promo} />

Error arising in my code. I am using React, NPM and styled components. What are the steps I need to take?

import React, { Component } from "react";
import Product from "./Product";
import Title from "./Title";
import { ProductConsumer } from "../context";
export default class Productlist extends Component {
render() {
return (
<React.Fragment>
<div className="py-5">
<div className="container">
<Title name="our" title="products" />
<div className="row">
<ProductConsumer>
{value => {
return value.products.map(product => {
return <Product key={product.id} product={product} />;
});
}}
</ProductConsumer>
</div>
</div>
</div>
</React.Fragment>
);
}
}
Okay, I am getting this error and I am not quite sure what it is since I am so new to working with React.JS. could someone assist me in figuring out what may be happening.
export default class Product extends Component {
render() {
const { id, title, img, price, inCart } = this.props.product;
return (
<ProductWrapper className="col-9 mx-auto col-md-6 col-lg-3 my-3">
<div className="card">
<div
className="img-container p-5"
onClick={console.log("you clicked me on the image container")}
>
<Link to="/details">
<img src={img} alt="product" className="card-img-top" />
</Link>
</div>
</div>
</ProductWrapper>
);
}
}
const ProductWrapper = styled.div
Above is the Product code as asked! Thank you!

React Router hide App content when click other pages link

I want to hide app component content when I click on other component pages link.
Right now, when I click other links like about us, then it shows both app component and about us page component. But I want show only about us content once I click on about us page.
Also, when I define App component patch as a "/" then application keeps loading.
Below are the code
App.js
import React, { Component } from "react";
import Navigation from "./components/Navigation";
import data from "./data";
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
// data: false
};
}
render() {
return (
<div className="container">
<Navigation />
{data.map((link) => (
<div className="card mb-3" key={link.Title}>
<div className="row no-gutters">
<div className="col-md-5">
<img
src={require("./images/" + link.Img)}
className="card-img"
alt=""
/>
</div>
<div className="col-md-7">
<div className="card-body">
<h5 className="card-title">{link.Title}</h5>
<p className="card-text">{link.Desc.halfDesc}</p>
<p className="card-text">
<small className="text-muted">{link.date}</small>
</p>
<button type="button" className="btn btn-dark float-right">
Read More
</button>
</div>
</div>
</div>
<FullDescription />
</div>
))}
</div>
);
}
}
const FullDescription = (props) => (
<div className="modalbox">
<p>fsdf</p>
</div>
);
export default App;
Navigation.Js Everything is working fine only App home page content show which i don't want when i click other pages
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import Api from "./Api";
import News from "./News";
import Website from "./Website";
class Navigation extends Component {
render() {
return (
<Router>
<ul className="nav justify-content-center mb-4 navigation">
<li className="nav-item">
<Link className="nav-link" to="/Api">
Api
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/News">
News
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/Website">
Website
</Link>
</li>
</ul>
<Switch>
<Route exact path="/Api" component={Api}></Route>
<Route exact path="/News" component={News}></Route>
<Route exact path="/Website" component={Website}></Route>
</Switch>
</Router>
);
}
}
export default Navigation;
For this to work you need to put content of app.js inside another component because right now it doesnt have a route to hide itself when going to other page. So you need to treat the component just like your rest components (Api.js, News.js) etc..
NewAppComponent.js
import React, { Component } from "react";
import { Link } from "react-router-dom";
class Navigation extends Component {
render() {
return (
<ul className="nav justify-content-center mb-4 navigation">
<li className="nav-item">
<Link className="nav-link" to="/Api">
Api
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/News">
News
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/Website">
Website
</Link>
</li>
</ul>
);
}
}
export default Navigation;
App.js
import React, { Component } from "react";
import Navigation from "./components/Navigation";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import NewAppComponent from "./NewAppComponent";
import Api from "./Api";
import News from "./News";
import Website from "./Website";
class App extends Component {
render() {
return (
<div className="container">
<Router>
<Navigation />
<Switch>
<Route exact path="/" component={NewAppComponent}></Route>
<Route path="/Api" component={Api}></Route>
<Route path="/News" component={News}></Route>
<Route path="/Website" component={Website}></Route>
</Switch>
</Router>
</div>
);
}
}
export default App;
NewAppComponent.js
// NewAppComponent.js
import React, { Component } from "react";
import data from "./data";
class NewAppComponent extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
// data: false
};
}
render() {
return (
<div className="container">
{data.map((link) => (
<div className="card mb-3" key={link.Title}>
<div className="row no-gutters">
<div className="col-md-5">
<img src={require("./images/" + link.Img)} className="card-img" alt="" />
</div>
<div className="col-md-7">
<div className="card-body">
<h5 className="card-title">{link.Title}</h5>
<p className="card-text">{link.Desc.halfDesc}</p>
<p className="card-text">
<small className="text-muted">{link.date}</small>
</p>
<button type="button" className="btn btn-dark float-right">
Read More
</button>
</div>
</div>
</div>
<FullDescription />
</div>
))}
</div>
);
}
}
const FullDescription = (props) => (
<div className="modalbox">
<p>fsdf</p>
</div>
);
export default NewAppComponent;

Categories

Resources