Next js Problem with sending props in through - javascript

So i have three files, and i am using Next.Js.
Those 3 files are _app.js, Layout.js, Navbar.js
_app.js
import '../styles/globals.css'
import '../styles/navbar.css'
import Layout from '../components/Layouts/Layout'
function MyApp({ Component, pageProps }) {
return (
<Layout primary_super='darkMode_Primary' secondary_super='darkMode_Secondary'>
<Component {...pageProps} />
</Layout>
)
}
export default MyApp
Layout.js
import Navbar from '../comps/Navbar'
import pt from 'prop-types';
export default function Layout({ children }, props) {
return (
<>
<Navbar primary={props.primary_super} secondary={props.secondary_super}/>
<main>{children}</main>
</>
)
}
Layout.pt = {
primary_super: pt.string,
secondary_super: pt.string,
};
Layout.defaultProps = {
primary_super: 'darkMode_Primary',
secondary_super: 'darkMode_Secondary',
}
Navbar.js
import theme from "../Data/theme"
import pt from 'prop-types';
export default function Navbar(props) {
const Primary = theme[props.primary]
const Secondary = theme[props.secondary]
return (
<div class="NAV" id="NAV" style={Primary}>
<div class="NAV_BOX_FULL NAV_LEX" style={Secondary}>
<img src="/NAV_img/cat.png" alt="" class="NAV_logo1 NAV_logo"/>
<h3 class="NAV_head">SilenxIka</h3>
</div>
<hr class="NAV_block"/>
<div class="NAV_BOX">
<img src="/NAV_img/home.png" alt="" class="NAV_logo"/>
<h3 class="NAV_head">Home</h3>
</div>
<div class="NAV_BOX">
<img src="/NAV_img/discord.png" alt="" class="NAV_logo"/>
<h3 class="NAV_head">Discord</h3>
</div>
<div class="NAV_BOX">
<img src="/NAV_img/about.png" alt="" class="NAV_logo"/>
<h3 class="NAV_head">About</h3>
</div>
<div class="NAV_BOX">
<img src="/NAV_img/projects.png" alt="" class="NAV_logo"/>
<h3 class="NAV_head">Projects</h3>
</div>
<div class="NAV_BOX">
<img src="/NAV_img/contact.png" alt="" class="NAV_logo NAV_SUS"/>
<h3 class="NAV_head">Contact Me</h3>
</div>
</div>
)
}
Navbar.pt = {
primary: pt.string,
secondary: pt.string,
};
All i want to do is, do some logic in _app.js then send two strings into Layout.js and then finally in Navbar.js to access those two strings, as you can see i tried to use props but it didn't work well.

Related

Error while moving on to other page in react

Currently am writing a full stack website, which uses Nodejs and Mongodb for Backend and reactjs for Frontend. I am having a problem in react. As I am new to developing, my explanation of the problem won't be accurate, forgive me for this.
Coming to the error, when am at my home page, it gets every picture and all the stuff perfectly, but when I go to profile page, the pictures wont get updated and they wont appear. I don't know why, please help me....
This is my feed page
import "./feed.css";
import Post from "../post/Post";
import Share from "../share/Share";
import { useState } from "react";
import { useEffect } from "react";
import axios from 'axios';
export default function Feed({username}) {
const [posts,setPosts]=useState([]);
const [texts,setTexts]=useState([]);
useEffect(()=>{
const fetchPosts=async ()=>{
const res=username?
await axios.get("posts/profile/"+username):
await axios.get("posts/timeline/63c29c2fe9a410383d4bcb98");
setPosts(res.data);
};
fetchPosts();
},[]);
return (
<div className="feed">
<div className="feedWrapper">
<Share/>
{posts.map((p)=>(
<Post key={p._id} post={p}/>
))}
</div>
</div>
)
}
This is my Profile.jsx
import "./profile.css"
import Topbar from "../../components/topbar/Topbar";
import Sidebar from "../../components/sidebar/Sidebar";
import Feed from "../../components/feed/Feed";
import Rightbar from "../../components/rightbar/Rightbar";
import { useEffect } from "react";
import axios from "axios";
import { useState } from "react";
export default function Profile() {
const [user,setUser]= useState({});
useEffect(()=>{
const fetchUser=async ()=>{
const res=await axios.get(`/users/?username=Bannu`);
setUser(res.data);
};
fetchUser();
},[]);
return (
<>
<Topbar/>
<div className="profile">
<Sidebar/>
<div className="profileRight">
<div className="profileRightTop">
<div className="profileCover">
<img className="profileCoverImg" src={user.coverPicture||"assets/person/noCover.jpeg"} alt="" />
<img className="profileUserImg"src="assets/person/7.jpeg" alt="" />
</div>
<div className="profileInfo">
<h4 className="profileInfoName">{user.username}</h4>
<span className="profileInfoDesc">{user.desc}</span>
</div>
</div>
<div className="profileRightBottom">
<Feed username='Bannu'/>
<Rightbar user={user}/>
</div>
</div>
</div>
</>
)
}
This is Post.jsx
import "./post.css";
import { MoreVert } from "#material-ui/icons";
import axios from 'axios';
import { useState,useEffect } from "react";
import {format} from 'timeago.js';
import { Link } from "react-router-dom";
export default function Post(post) {
const [like,setLike]=useState(post.post.likes.length);
const [isLiked,setIsLiked]=useState(false);
const [user,setUser]=useState({});
const likeHandler=()=>{
setLike(isLiked?like-1:like+1);
setIsLiked(!isLiked);
};
useEffect(()=>{
const fetchUser=async ()=>{
const res=await axios.get(`/users?userId=${post.post.userId}`);
setUser(res.data);
};
fetchUser();
},[post.post.userId]);
return (
<div className="post">
<div className="postWrapper">
<div className="postTop">
<div className="postTopLeft">
<Link to={`profile/${user.username}`}>
<img className="postProfileImg"src={user.profilePicture||"assets/person/noAvatar.jpeg"} alt="" />
</Link>
<span className="postUsername">{user.username}</span>
<span className="postDate">{format(post.post.createdAt)}</span>
</div>
<div className="postTopRight">
<MoreVert/>
</div>
</div>
<div className="postCenter">
<span className="postText">{post?.desc}</span>
<img className="postImg" src={post.post.img} alt="" />
</div>
<div className="postBottom">
<div className="postBottomLeft">
<img className="likeIcon" src="assets/like.png" onClick={likeHandler} alt="" />
<img className="likeIcon"src="assets/heart.jpeg" onClick={likeHandler} alt="" />
<span className="postLikeCounter">{like} people like it</span>
</div>
<div className="postBottomRight">
<span className="postCommentText">{post.comment} comments</span>
</div>
</div>
</div>
</div>
)
}
This is share.jsx
import "./share.css"
import {PermMedia,Label, Room, EmojiEmotions} from '#material-ui/icons'
export default function Share() {
return (
<div className="share">
<div className="shareWrapper">
<div className="shareTop">
<img className="shareProfileImg" src="assets/person/1.png" alt="" />
<input type="text"
placeholder="What's in your mind?"
className="shareInput"
/>
</div>
<hr className="shareHr" />
<div className="shareBottom">
<div className="shareOptions">
<div className="shareOption">
<PermMedia htmlColor="tomato" className="shareIcon"/>
<span className="shareOptionText">Photo or Video</span>
</div>
<div className="shareOption">
<Label htmlColor="blue"className="shareIcon"/>
<span className="shareOptionText">Tag</span>
</div>
<div className="shareOption">
<Room htmlColor="green" className="shareIcon"/>
<span className="shareOptionText">Location</span>
</div>
<div className="shareOption">
<EmojiEmotions htmlColor="goldenrod" className="shareIcon"/>
<span className="shareOptionText">Feeling</span>
</div>
</div>
<button className="shareButton">Share</button>
</div>
</div>
</div>
)
}
And these are the pictures of home and particular profile pages Home Particular profile page. You can observe that in the profile page the image of a post is missing.
Help me ....

How to pass a state to a Parent component if I have a button triggering the state in the 2nd Child in React

Hi there,
The issue that I faced recently is the next:
I have a parent component MainPage, that has child components ModalJoin (is not shown by default) and ExploreProjects in it. This ExploreProjects component has its own child component ProjectCard which has a button that is supposed to change a state so ModalJoin is shown.
Does anyone have a solution of how do I bind all these, so when the button is clicked ->useState changes to true and ModalJoin pops up? Been trying to link them properly the whole day but still didn't find a solution.
Would appreciate any help!
Have the following files:
Main page
import React, {useState} from 'react'
import ExploreProjects from './ExploreProjects'
import ModalJoin from './ModalJoin'
export default function MainPage() {
const [isOpened, setIsOpened] = useState(false)
return (
<div>
<div className='app'>
<div className="app__body">
<ExploreProjects/>
</div>
</div>
<ModalJoin openModal={isOpened} onClose={() => setIsOpened(false)}/>
</div>
)
}
ExploreProjects
import React from 'react'
import './ExploreProjects.css'
import ProjectCard from './ProjectCard'
function ExploreProjects() {
return (
<div className='explore__projects'>
<div className="filters__section">
<div className='filter__item'>
<h3>Location</h3>
<img src="/images/chevronDown.svg" alt=""/>
</div>
<div className='filter__item'>
<h3>Industry</h3>
<img src="/images/chevronDown.svg" alt=""/>
</div>
<div className='filter__item'>
<h3>Company</h3>
<img src="/images/chevronDown.svg" alt=""/>
</div>
<div className='filter__item'>
<h3>Complexity</h3>
<img src="/images/chevronDown.svg" alt=""/>
</div>
<div className='filter__item'>
<h3>Duration</h3>
<img src="/images/chevronDown.svg" alt=""/>
</div>
</div>
<div className="projects__section">
<ProjectCard />
<ProjectCard />
<ProjectCard />
<ProjectCard />
<ProjectCard />
<ProjectCard />
</div>
</div>
)
}
export default ExploreProjects
ProjectCard
import React, {useState} from 'react'
import './ProjectCard.scss'
export default function ProjectCard({ src, logo, headline, companyName,
complexity, description, projectType, tag }) {
const [setIsOpened] = useState(false)
return (
<div className='project__card'>
<div className="project__card__header">
<img src="/images/rehauIcon.png" alt="" className='company__logo' />
<h3>Logistics Project</h3>
<div className="project__card__company">
<img src="/images/buildingIcon.svg" alt="" />
<p>Rehau</p>
<p>/</p>
<img src="/images/locationIcon.svg" alt="" />
<p>Berlin</p>
</div>
<div className="project__card__complexity">
<div className="basic__complexity"></div>
<p>Basic</p>
</div>
</div>
<div className="project__card__body">
<div>
<h3>Task:</h3>
</div>
<span>Text
<button>More</button>
</span>
</div>
<div className="project__card__bottom">
<div className="project__card__time">
<p>15m ago</p>
</div>
<div className="project__card__recruitment">
<p>Job opportunity</p>
</div>
<div className="project__card__teams">
<p>1/2 teams joined</p>
</div>
<div className="project__card__tag">
<p>#supplychain</p>
</div>
</div>
<div className="project__card__right">
<img src="images/imgHero.png" alt="" className='project__video__info' />
<div onClick={ () => this.setIsOpened(true)} className="join__project__button">
<p>Join</p>
</div>
</div>
</div>
)
}
ModalJoin
import React from 'react'
export default function ModalJoin({openModal, onClose}) {
if (!openModal) return null
return (
<div>
<button onClick={onClose}>Close</button>
HEEEYYYYYY
</div>
)
}
I commented:
You'll need to pass a callback prop down <ExploreProjects onOpenModalJoin={callback} />, and then pass the same callback down from ExploreProjects down to ProjectCard. Then in project card on the button click, you would call that callback.
This is a more full explanation:
export default function MainPage() {
const [isOpened, setIsOpened] = useState(false);
const callback = () => setIsOpened(true);
...
<ExploreProjects onOpenModalJoin={callback} />
function ExploreProjects(props) {
...
<ProjectCard onOpenModalJoin={props.onOpenModalJoin} />
...
And then inside ProjectCard, you would have
onClick={props.onOpenModalJoin}
Lets go with a simple example on how to change state of a parent from a child and manipulate conditional rendering. you have to pass setState to the child and subChild as well and call it from there. That changes parent state and reflects on modal.
Code Sandbox => https://codesandbox.io/s/silent-bush-c6v4d?file=/src/App.js:0-992
Here you go, this should fix your issue.
import React, { useState } from "react";
import "./styles.css";
const ModalJoin = ({ open, close }) => {
const modal = open ? (
<div style={{ background: "pink" }}>
I am ModalJoin
<button onClick = {close}> Close Me</button>
</div>
) : null;
return modal;
};
const ExploreProjects = ({ click }) => {
return (
<div style={{ background: "orange" }}>
I am ExploreProjects
<ProjectCard click={click} />
</div>
);
};
const ProjectCard = ({ click }) => {
return (
<div style={{ background: "grey" }}>
I am ProjectCard
<button onClick={click}>click me to open modal </button>
</div>
);
};
const App = () =>
{
const [modal, setModal] = useState(false)
return (
<div className="App" style={{ background: "lightBlue" }}>
<h1>I am Parent</h1>
<ExploreProjects click = {() => setModal(true)}/>
<ModalJoin open={modal} close={() => setModal(false)} />
</div>
);
};
export default App;

Functional component is not being rendered

I am trying to display the songs but for some reason my songs component is not even being executed. The console.log statement inside the Songs component is also not being logged to console. Also no errors of any sort are detected at all.
Here is my body component from which I am calling the Songs component
import './body.css'
import React from 'react'
import Header from './Header'
import { useStateValue } from './StateProvider';
import FavoriteIcon from '#material-ui/icons/Favorite';
import PlayCircleFilledIcon from '#material-ui/icons/PlayCircleFilled';
import MoreHorizIcon from '#material-ui/icons/MoreHoriz';
import Songs from './Songs.js'
function Body( {spotify}) {
const [{recently_played},dispatch] = useStateValue();
return (
<div className="body">
<Header spotify={spotify} />
<div className="body__info">
<img src={recently_played?.images[0].url} alt=""/>
<div className="body__infotext">
<strong>PLAYLIST</strong>
<h2>On Repeat</h2>
<p>{recently_played?.description}</p>
</div>
</div>
<div className="body__songs">
<div className="body__icons">
<PlayCircleFilledIcon className="body__shuffle"/>
<FavoriteIcon fontSize="large"/>
<MoreHorizIcon />
</div>
{recently_played?.tracks.items.map(item=>{
<Songs track={item.track} />
})}
</div>
</div>
)
}
export default Body
Here is the Songs component
import React from "react";
import './SongRow.css'
function Songs({ track }) {
console.log(track);
return (
<div className="songRow" >
<img className="songRow__album" src={track.album.images[0].url} alt="" />
<div className="songRow__info">
<h1>{track.name}</h1>
<p>
{track.artists.map((artist) => artist.name).join(", ")} -{" "}
{track.album.name}
</p>
</div>
</div>
);
}
export default Songs;
You are not returning anything inside the map
{recently_played?.tracks.items.map(item => {
return <Songs track={item.track} />;
})}
[or] use the shorthand version of arrow function
{recently_played?.tracks.items.map(item => <Songs track={item.track} />)}

How can I use nested routes with props for a child component

I'm building an react app where I have a feed component and the feed component consists of array of post components. The post component contains a link in it for viewing the full post component. I'm not able to pass the respective props to the full post component. I'm not able to do a nested route for the fullpost component.
this is my layout component
import React, { Component } from "react";
import Header from "../Header/Header";
import classes from "./Layout.css";
import { Route, Switch } from "react-router-dom";
import FullPost from "../Feed/FullPost/FullPost";
import axios from "axios";
import Feed from "../Feed/Feed";
class Layout extends Component {
state = {
users: [],
};
componentDidMount() {
axios
.get("https://goodwill-60d8a.firebaseio.com/Users.json")
.then((response) => {
this.setState({ users: response.data });
});
}
render() {
console.log(this.state.users);
return (
<div className={classes.main}>
<div>
<Header />
</div>
<div className={classes.content}>
<Switch>
<Route
path="/"
exact
render={() => <Feed users={this.state.users} />}
/>
<Route path="/fullpost" exact render={() => <FullPost />} />
</Switch>
</div>
</div>
);
}
}
export default Layout;
FEED component
import React from "react";
import Post from "./Post/Post";
import classes from "./Feed.css";
const feed = (props) => {
const feedItems = Object.keys(props.users).map((key) => ({
id: key,
...props.users[key],
}));
return (
<div className={classes.feed}>
{feedItems.map((items) => (
<Post
key={items.id}
profilename={items.profileName}
profilepic={items.profilePic}
timestamp={items.timeStamp}
contentimage={items.contentImage}
contenttext={items.contentText}
trend={items.trend}
></Post>
))}
</div>
);
};
export default feed;
Post component
import React from "react";
import classes from "./Post.css";
import ShareButton from "../../UI/ShareButton/ShareButton";
import { Link } from "react-router-dom";
const post = (props) => {
return (
<div className={classes.post}>
<div className={classes.header}>
<div className={classes.profileimage}>
<img className={classes.pic} src={props.profilepic} alt="" />
</div>
<div className={classes.name}>{props.profilename}</div>
<div className={classes.timestamp}>{props.timestamp}</div>
</div>
<div className={classes.container}>
<div className={classes.image}>
<img src={props.contentimage} alt="" />
</div>
<div>
<div className={classes.text}>
<span>{props.contenttext}</span>
</div>
<div className={classes.fullpost}>
<Link to="/fullpost" {...props}>
See Full Post
</Link>
</div>
</div>
</div>
<div className={classes.footer}>
<div className={classes.trend}>
<span>{props.trend}</span>
</div>
<ShareButton />
</div>
</div>
);
};
export default post;
Full Post component
import React from "react";
import classes from "./FullPost.css";
import pic from "../../../Assets/Images/self.jpg";
import { Link } from "react-router-dom";
const fullPost = (props) => {
return (
<div className={classes.fullpost_container}>
<div className={classes.photo_container}>
<img src={props.profilepic} alt=" " />
</div>
<div className={classes.sidebar}>
<div className={classes.profileimage}>
<img src={props.profilePic} alt="" />
</div>
<div className={classes.profilename}>Tony Kroos</div>
<div className={classes.timestamp}>3 Hours Ago</div>
</div>
<div className={classes.feedlink}>
<Link to="/" className={classes.feedlink_text}>
See more posts
</Link>
</div>
</div>
);
};
export default fullPost;

Components not re-rendering on route change - React HashRouter

I've got a problem with react and react-router.
When I click on a link (in my example contact in Footer.js), the url changes, but the desired component Location is not shown. When I refresh the site then, the correct component is displayed.
App.js:
import React, { Component } from 'react';
import { BrowserRouter as Router, HashRouter, Route, Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.css';
import Footer from './Footer.js';
import Navigation from './Navigation.js';
import Background from './Background.js';
import Home from './Home.js';
import Products from './Products.js';
import Industries from './Industries.js';
import Partner from './Partner.js';
import Location from './Location.js';
import MeetUs from './MeetUs.js';
import ScrollUp from './ScrollUp.js';
import Divider from './Divider.js';
import Country from './Country.js';
import Language from './Language.js';
import Waypoint from 'react-waypoint';
import $ from "jquery";
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentLanguage: 'en',
currentBU: '',
currentIndustry: '',
showMainProductGroups: false,
currentCountry: 'group',
countryObject: Country['group'],
contacts: [],
mainProductGroups: [],
};
}
handleCountryChange() {
//...
}
handleLanguageChange() {
//...
}
handleBUChange() {
//...
}
render() {
const routes = [
{
path: '/',
exact: true,
components: () =>
<div>
<Home key="home" currentLanguage={this.state.currentLanguage} />
</div>,
},
{
path: '/contact',
exact: true,
components: () => <Location key="locations" currentLanguage={this.state.currentLanguage} country={this.state.countryObject} contacts= {this.state.contacts} onCountryChange={this.handleCountryChange.bind(this)} />
},
]
return (
<HashRouter>
<div>
<Background />
<div id="wrap">
<div id="main" className="container clear-top marginBottom50px">
<div id="content">
<Navigation key="navBar" currentLanguage={this.state.currentLanguage} onLanguageChange={this.handleLanguageChange.bind(this)} onBUChange={this.handleBUChange.bind(this)} onCountryChange={this.handleCountryChange.bind(this)} />
{
routes.map((route, index) => (
<Route key={index} path={route.path} exact={route.exact} component={route.components} />
))
}
</div>
</div>
</div>
<Footer key="footer" currentLanguage={this.state.currentLanguage} />
<ScrollUp key="scrollUp" />
</div>
</HashRouter>
);
}
}
export default App;
Home.js:
import React, { Component } from 'react';
import $ from "jquery";
import { Link } from 'react-router-dom';
import {withRouter} from 'react-router';
import Language from './Language.js';
import locations from './locations.jpg';
import locationLegend from './locationLegend.jpg';
require('bootstrap')
class Home extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div className="container marginTop50px marginBottom50px area">
<div className="row">
<div className="col-12 text-center animDelay2 fadeInDown animated">
<h1>International Distribution of Specialty Chemicals</h1>
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center animDelay2 fadeInUp animated">
{Language[this.props.currentLanguage].homeStartText}
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center">
<img src={locations} className="img-fluid" alt="Locations" />
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center">
<img src={locationLegend} className="img-fluid" alt="Locations" />
</div>
</div>
</div>
);
}
}
export default withRouter(Home);
Location.js:
import React, { Component } from 'react';
import $ from "jquery";
import { Link } from 'react-router-dom';
import Language from './Language.js';
import Country from './Country.js';
import ContactPerson from './ContactPerson.js';
import locations from './locations.png';
import phone from './phoneBlack.svg';
import fax from './faxBlack.svg';
import email from './emailBlack.svg';
import {withRouter} from 'react-router';
require('bootstrap');
class Location extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('Country change:' + this.props.country.key);
$('#selectCountry').val(this.props.country.key); //name['en']
}
onCountryChange() {
let countryName = this.refs.country.value;
this.props.onCountryChange(countryName);
}
render() {
return (
<div className="container marginTop50px marginBottom50px area" id="locations">
<div className="row">
<div className="col-12 text-center">
<h2>{Language[this.props.currentLanguage].locations}</h2>
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center">
<div className="form-group">
<select id="selectCountry" className="form-control" ref="country" onChange={this.onCountryChange.bind(this)}>
<option defaultValue>{Language[this.props.currentLanguage].selectLocation.toUpperCase()}</option>
{
Object.keys(Country).map((countryKey) => {
const country = Country[countryKey];
return (
<option value={countryKey} key={"loc" + countryKey}>{country.name[this.props.currentLanguage].toUpperCase()}</option>
);
})
}
</select>
</div>
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center">
{this.props.country.name[this.props.currentLanguage].toUpperCase()}
<br />
<address>
<span dangerouslySetInnerHTML={{__html: this.props.country.address}}></span>
<br />
<br />
<img src={phone} alt="Anrufen" className="phoneMain"></img><span> </span>
<a href={this.props.country.phoneHTML}>{this.props.country.phone}</a>
<br />
<img src={fax} alt="Fax" className="phoneMain"></img><span> </span>
<a href={this.props.country.faxHTML}>{this.props.country.fax}</a>
<br />
<img src={email} alt="Email" className="emailMain"></img><span> </span>
<a href={"mailto://" + this.props.country.email}>{this.props.country.email}</a>
</address>
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center">
{Language[this.props.currentLanguage].vatRegistrationNumber + ": " + this.props.country.vatNo}
<br />
{Language[this.props.currentLanguage].registrationOffice + ": "}
<span dangerouslySetInnerHTML={{__html: this.props.country.registrationOffice}}></span>
</div>
</div>
<div className="row marginTop50px">
<div className="col-12 text-center">
<h3>{Language[this.props.currentLanguage].contact}</h3>
</div>
</div>
<div className="row">
{
this.props.contacts.map((contact) => {
return (
<div className="col-12 col-sm-12 col-md-12 col-lg-6 text-center">
<ContactPerson contact={contact} key={"contact" + contact.id} />
</div>
);
})
}
</div>
</div>
);
}
}
export default withRouter(Location);
Footer.js:
import React, { Component } from 'react';
import $ from "jquery";
import { Link } from 'react-router-dom';
import {withRouter} from 'react-router';
import Language from './Language.js';
import phone from './phoneWhite.svg';
import fax from './faxWhite.svg';
require('bootstrap');
class Footer extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<footer className="footer">
<div className="container-fluid borderTop1px footerLayout">
<div className="row">
<div className="col-3">
<address>
<small>
Some text
</small>
</address>
</div>
<div className="col-6 text-center">
<div className="row">
<div className="col-12 col-sm-12 col-md-12 col-lg-3 text-center">
<small>{Language[this.props.currentLanguage].download}</small>
</div>
<div className="col-12 col-sm-12 col-md-12 col-lg-3 text-center">
<Link to="/imprint" className="nav-link footerLink"><small>{Language[this.props.currentLanguage].imprint}</small></Link>
</div>
<div className="col-12 col-sm-12 col-md-12 col-lg-3 text-center">
<Link to="/contact" className="nav-link footerLink"><small>{Language[this.props.currentLanguage].contact}</small></Link>
</div>
<div className="col-12 col-sm-12 col-md-12 col-lg-3 text-center">
<Link to="/termsAndConditions" className="nav-link footerLink"><small>{Language[this.props.currentLanguage].termsAndConditions}</small></Link>
</div>
</div>
</div>
<div className="col-3">
<ul className="list-inline">
<li>
<img src={phone} alt="Anrufen" className="phone"></img> <small><a className="footerLink" href="tel:+49">+49</a></small>
</li>
<li>
<img src={fax} alt="Fax" className="phone"></img> <small><a className="footerLink" href="tel:+49">+49</a></small>
</li>
</ul>
</div>
</div>
</div>
</footer>
);
}
}
export default withRouter(Footer);
What I'm doing wrong? Why it is not working, when I click on a link?
Got it working now.
I needed to change <HashRouter> to <Router>. Then it works fine.
UPDATE:
This solution solves the problem, but then there is a different problem: When I have navigated and refresh the page, then an error (404) is thrown, because there is of course no such a page on the server.
I need to get the HashRouter work.
When you declare your routes in App.js, you should pass the props to the component:
components: props => <Location {...props} <insert other props> />
You should stick to the <Router> solution as having unnecessary hash in the url is ugly.
When I have navigated and refresh the page, then an error (404) is thrown, because there is of course no such a page on the server.
To resolve this, you need to set up a redirect to redirect all requests to the base url for the React app to handle (the url displayed will be preserved).
On Netlify, you can create a _redirects file in your public folder with the content:
/* /index.html 200
On AWS S3, the redirect rules can be set in S3 or CloudFront, see the answers here.
For Google Cloud bucket, see this.
For Github pages, see this.
In your Route component you use component prop to pass the Location component (instead of render or children props available on Route) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop.However in your case it seems you are using it for no reason so you should just pass the component and not an inline function that returns it like so :
const routes = [
{
path: '/',
exact: true,
components: <Home key="home" currentLanguage={this.state.currentLanguage}/>
},
{
path: '/contact',
exact: true,
components: <Location key="locations" currentLanguage={this.state.currentLanguage} country={this.state.countryObject} contacts= {this.state.contacts} onCountryChange={this.handleCountryChange.bind(this)} />
},
]
Make your routes use Component as below
import {IndexRoute, Route} from 'react-router';
<Route component={App}>
<Route path='/locations' component={LocationComponent}/>
</Route>
This is what I am doing in my current project without using HashRouter.
Currently, When you do
<Route key={index} path={route.path} exact={route.exact} component={route.components} />
I don't think {route.components} treats it as a component.
Could be a problem with withRouter().
Have you seen this?
https://github.com/ReactTraining/react-router/issues/5037

Categories