How to pass props to component with NavLink - reactjs

I am trying to send props to component with NavLink.
<NavLink to={{pathname :"/wind", state:{from: "This is my props"}}} >Wind</NavLink>
and I want to get it in this component,
import React from 'react';
import { useLocation} from "react-router-dom"
const Wind = () =>{
const location = useLocation();
const {from} = location.state;
console.log({from})
return (
<div className="Wind">
<h1>Wind</h1>
</div>
);
}
export default Wind;
unfortunatelly this give me result
so I try it like this
import React from 'react';
const Wind = (props) =>{
//console.log(props.location.state)
return (
<div className="Wind">
<h1>Wind</h1>
</div>
);
}
export default Wind;
console log in ths case is undefined.
I donĀ“t know why it is not working any ideas?

In the new version, the state is passed as a separate prop. Try using
<NavLink to={{pathname :"/wind"}}
state={{from: "This is my props"}} >Wind</NavLink>
And the component try fetching like this
import React from "react";
import { useLocation } from "react-router-dom";
const Wind = () => {
const location = useLocation();
const { state } = location;
console.log(state.from);
return (
<div className="Wind">
<h1>Wind</h1>
</div>
);
};
export default Wind;

Related

Showing white blank screen with the use of context api in React js

Showing white blank screen with the use of context api in React js
I'm running my code which has no errors, but when I take a trip to localhost:3000
I get a blank screen.
These are the React js files in the project, If I don't use the Context-API, coding is doing great.
App.js
import "./App.css";
import { UserContextProvider } from "./contexts/user";
import { Home } from "./pages";
function App() {
return (
<div className="app">
<UserContextProvider>
<Home />
</UserContextProvider>
</div>
);
}
export default App;
user.js
import { createContext, useState } from "react";
export const UserContext = createContext();
export const UserContextProvider = (props) => {
const [user, setUser] = useState(null); // user value can be used anywhere
return (
<UserContext.Provider value={{user: [user,setUser]}}>
{props.childern}
</UserContext.Provider>
);
};
SignInBtn.js
import React,{useContext} from "react";
import "./style.css";
import GoogleIcon from "#mui/icons-material/Google";
import { signInWithGoogle } from "../../services/auth";
import { UserContext } from "../../contexts/user";
const icon = {
fontSize: 14,
};
function SignInBtn() {
const [user, setUser] = useContext(UserContext).user;
const signInBtnClick = async () =>{
let userBySignIn = await signInWithGoogle()
if(userBySignIn) setUser(userBySignIn)
}
return (
<div className="signInBtn" onClick={signInBtnClick}>
<div className="btn">
<p>Signin with </p>
<GoogleIcon style={icon}/>
</div>
</div>
);
}
export default SignInBtn;
first of everything make sure your SignInBtn Component is children of Context Provider
secondly
Remove the .user from here
const [user, setUser] = useContext(UserContext).user; in SignInBtn.js Where you are taking value from UserContext.
You can do this way
const {user} = useContext(UserContext);
const [user, setUser] = user
Solution <>{props.children}</>
You should enclose {props.childern} in Fragments. or any other tags that do not return null in any case.
Refer to this. https://codesandbox.io/s/divine-shape-6rxws?file=/src/user.js:331-353 for the exact solution
you should import React in user.js
it will work

How to pass props from component to page. React/Nextjs

So I want to pass my navbar ref as a props to a page. But I don't know how to pass it, I migrated my project from cra to next, I'm basically a newbie, please if there's better way to do this, please tell me. Thank you!.
Here is my navbar component code
import React, { Fragment, useState, useEffect, useRef } from "react";
import Link from "next/link";
const NavBar = ({ navBarRefProps }) => {
const navBarRef = useRef();
useEffect(() => {
navBarRefProps(navBarRef.current);
},[navBarRef])
return(
<Fragment>
<nav ref={navBarRef}>
<ul>
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
</ul>
</nav>
</Fragment>
)
}
export default NavBar;
Here is my Layout component.
import React, { Fragment, useState, useEffect, useRef } from "react";
import { useRouter } from 'next/router';
import NavBar from "./../NavBar";
import MidNavBar from "./../MidNavBar";
import Banner from "./../Banner";
const Layout = ({ children, navBarRefProps }) => {
const navBarRef = useRef();
const router = useRouter();
const navBarRefPropsHandle = (props) => {
navBarRef.current = props.current;
navBarRefProps(navBarRef.current);
}
return(
<Fragment>
<div className="wrapper">
<NavBar navBarRefProps={ navBarRefPropsHandle } />
<div className="inner_wrapper">
<Banner/>
{
router.pathname !== "/" ?
<MidNavBar midNavBarRefProps = {midNavBarRefPropsHandle} dummyRefProps={dummyRefPropsHandle}/>
:
""
}
{ children }
</div>
</div>
</Fragment>
)
}
Here is my _app.js file
import 'react-app-polyfill/ie11';
import 'react-app-polyfill/stable';
import React , { useState, useRef, useEffect } from "react";
import Layout from "./../components/Layout";
import './../styles/css/index.css';
function MyApp({ Component, pageProps }) {
const navBarRef = useRef();
const setNavBarRefHandle = (props) => {
navBarRef.current = props;
}
return(
<Layout navBarRefProps={ setNavBarRefHandle }>
<Component {...pageProps} navBarRefProps={ navBarRef.current } />
</Layout>
)
}
export default MyApp;
Here is my home page or index.js file, where I want to use the navbar ref
import React, { Fragment, useEffect, useRef } from "react";
import ImageSlider from "./../components/ImageSlider ";
import About from "./../components/About";
import MidNavBar from "./../components/MidNavBar";
// I thought I could access the navBarRefProps if I passed it on the <Component> in _app.js but it's undefined
const Home = ({ navBarRefProps }) => {
const navBarRef = useRef();
const midNavBarRef = useRef();
useEffect(() => {
navBarRef.current = navBarRefProps;
},[navBarRefProps])
const stickMidNavBarHandle = () => {
console.log(navBarRef.current);
let navBarRefSize = navBarRef.offsetHeight;
}
useEffect(() => {
window.addEventListener("scroll",stickMidNavBarHandle );
return () => {
window.removeEventListener("scroll",stickMidNavBarHandle);
}
},[])
const midNavBarRefPropsHandle = (props) => {
midNavBarRef.current = props.current;
}
return(
<Fragment>
<ImageSlider/>
<MidNavBar midNavBarRefProps = {midNavBarRefPropsHandle}/>
<About />
</Fragment>
)
}
export default Home;
This is my file structure
root folder
.next
components
NavBar
-index.js
Layout
-index.js
MidNavBar
-index.js
pages
_app.js
index.js
about.js
about
-missionVision.js
public
images
videos
fonts
styles
Thank you!

Trying to pass props and state to a child component

I have a parent functional component and i need to pass props and state to a child functional component, i have managed to pass only one of theme (props or state), the code below displays the fetched data, firstly i've been using const Footer = ({name, adresse, phone}) => {} and then i've replaced it with const Footer = (props) => {} i thought i can pass them this way!!
{props.colorScheme} is accessible in App.js but not in Footer component, should i use context API to pass the props?
FYI, here is my index.js :
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const colorScheme = root_el.getAttribute("color-scheme");
ReactDOM.render(
<App customBackground={customBackground} colorScheme={colorScheme} />,
root_el
);
My App component
import React, {useEffect, useState, Suspense, lazy } from 'react';
import axios from 'axios';
import Footer from "./components/Footer";
const App = (props) => {
const [infos, setInfos] = useState({});
useEffect( () => {
loadData();
}, []);
const loadData = () => {
axios.get(`https://api`)
.then((res) => {
console.log(res.data);
const infs = setInfos(res.data);
});
}
return (
<div>
<Footer name={infos.name} adresse={infos.adresse} phone= {infos.phone}
</div>
)
};
export default App;
My child component :
import React from 'react';
const Footer = (props) => {
const {name, adresse, phone} = props;
return (
<div>
<h3>{props.colorScheme}</h3>
<span>{name}<span>
<span>{adresse}<span>
<span>{phone}<span>
</div>
)
}
export default Footer;
You can continue to pass the props down to the footer component or you can, as you point out, use a context. Passing the colorScheme via the props is shown below.
Note: Your code was displaying the colorScheme as an h3 in the Footer and I left that as is.
Updated App Component:
import React, {useEffect, useState, Suspense, lazy } from 'react';
import axios from 'axios';
import Footer from "./components/Footer";
const App = (props) => {
const [infos, setInfos] = useState({});
const { colorScheme } = props;
useEffect( () => {
loadData();
}, []);
const loadData = () => {
axios.get(`https://api`)
.then((res) => {
console.log(res.data);
const infs = setInfos(res.data);
});
}
// Footer tag below was missing the tag's closing
// Added colorScheme prop
return (
<div>
<Footer
colorScheme={colorScheme}
name={infos.name}
adresse={infos.adresse}
phone= {infos.phone}/>
</div>
)
};
export default App;
Updated Footer
import React from 'react';
const Footer = (props) => {
const {name, adresse, phone, colorScheme} = props;
return (
<div>
<h3>{colorScheme}</h3>
<span>{name}<span>
<span>{adresse}<span>
<span>{phone}<span>
</div>
)
}
export default Footer;
You can also create a new Context using createContext and useContext so that you can have a single way for all your components to access it. You won't have to pass the color scheme through props. You may want to do both so that you have a global set of default colors and then a prop that lets you override them.

How to show my data in Unordered list format in React?

I am working on a React project, In my project I have four components those are App, Componentc,
Componente, Componentf. Now I am trying to pass an Array from App to Componentf using Context API
I successfuly passed an Array, but the problem is in output the Array is showing like side by
side. but what I am expecting it has to show like Unordered list in html
Please help me to acheive this
This is App.js
import React from 'react';
import Componentc from './Componentc/Componentc';
// import './App.css';
export const UserContext = React.createContext()
const fruits = ['Apple','Orange','Banana','Grapes']
function App() {
return (
<div className="App">
<UserContext.Provider value={fruits}>
<Componentc></Componentc>
</UserContext.Provider>
</div>
);
}
export default App;
This is Componentc
import React from 'react';
import './Componentc.css';
import Componente from '../Componente/Componente';
const Componentc = () => {
return(
<Componente></Componente>
)
}
export default Componentc
This is Componente
import React from 'react';
import './Componente.css';
import Componentf from '../Componentf/Componentf';
const Componente = () => {
return(
<Componentf></Componentf>
)
}
export default Componente
This is Componentf
import React from 'react';
import './Componentf.css';
import { UserContext } from '../App'
const Componentf = () => {
return (
<div>
<UserContext.Consumer>
{
user => {
return <div className='d-block'>{user}</div>
}
}
</UserContext.Consumer>
<h1>Component F</h1>
</div>
)
}
export default Componentf
The value of your context is an array, but you are treating it like an object in the context consumer.
You only need to change return <div className='d-block'>{user}</div> by :
{user => {
return user.map(t => (
<div key={t} className="d-block">
{t}
</div>
));
}}
Although your variables should have meaningful names; I recommend changing the name of the user context and variable to be fruits.
Also, If you are using a recent react version (> 16.8), I also recommend that you use React.useContext API to receive values from context, code become more readable.
const Componentf = () => {
const fruits = React.useContext(FruitContext);
return (
<div>
{fruits.map(fruit => (
<div key={fruit} className="d-block">
{fruit}
</div>
))}
<h1>Component F</h1>
</div>
);
};
Here is a codesandbox demo

Why the mapStateToProps returns "undefined" in React/Redux

Why the function mapStateToProps returns "undefined" or empty object in React/Redux.
My code:
import React from 'react'
import {connect} from "react-redux";
export const ArticleComponent = ({props}) => (
<div>
<h1>Hello {console.log(props)}</h1>
</div>
);
const mapStateToProps = (state) => {
return {
text: '11111'
}
};
export default connect(mapStateToProps)(ArticleComponent);
You made multiple mistakes in your code :
You export your initial component AND you make a default export to the connected component.
Remove the export on the initial component and import your default export with :
import ArticleComponent from "./ArticleComponent" // No curly braces{ } to import the default;
You're accessing props.props (which is undefined) by doing const ArticleComponent = ({props}) =>
Remove curly braces to access all props passed to this component : const ArticleComponent = (props) =>(or use curly braces to get only the {text} prop)
You log the props in console (this is not an error but I don't think this is intentional)
Display the state like this : <h1>Hello {props.text}</h1>
Here's the full code :
import React from 'react'
import {connect} from "react-redux";
const ArticleComponent = ({text}) => ( // or (props)
<div>
<h1>Hello {text}</h1> // or {props.text}
</div>
);
const mapStateToProps = (state) => {
return {
text: '11111'
}
};
export default connect(mapStateToProps)(ArticleComponent);
In order for the props to be received properly you need to use the connected instance of the component. Import it as a default import since connected component is the default export.
import ArticleComponent from 'path/to/ArticleComponent'
I didn't understand why you want to extract props from props.
Instead of
export const ArticleComponent = ({props})
Write
const ArticleComponent = (props)
you can't use a const like this it will never work. And why are you returning a text value (is this just to test it)?
import React, {Component} from 'react'
import {connect} from "react-redux";
class ArticleComponent extends Component {
render() {
const {text} = this.props
return (
<div>
<h1>Hello {console.log(text)}</h1>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
text: '11111'
}
};
ArticleComponent = connect(mapStateToProps)(ArticleComponent);
export default ArticleComponent;

Resources