Why this problem happend in my react function? - reactjs

I'm trying to get information from redux but this error happen and i dont know how could i fix it. That's my first time with react and react Hooks, sorry but i'm lost.
Thank you in advance.
React Hook "useSelector" is called in function "header" which is neither a React function component or a custom React Hook function
My code:
import React from 'react';
import { useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import Notifications from '../Notifications';
import logo from '~/assets/headerLogo.svg';
import { Container, Profile, Content } from './styles';
export default function header() {
const profile = useSelector(state => state.user.profile);
return (
<Container>
<Content>
<nav>
<img src={logo} alt="GoBarber" />
<Link to="/dashboard">DASHBOARD</Link>
</nav>
<aside>
<Notifications />
<Profile>
<div>
<strong>{profile.name}</strong>
<Link to="/profile">Meu Perfil</Link>
</div>
<img
src={
profile.avatar.url ||
'https://api.adorable.io/avatars/50/abott#adorable.png'
}
alt="profile"
/>
</Profile>
</aside>
</Content>
</Container>
);
}

The rules of hooks lint plugin depends on naming conventions to tell what is a component, what is a hook, and what is any other function. Functions beginning with use (eg, useEffect, useMyCustomStuff) are assumed to be hooks. Functions beginning with a capital letter are assumed to be components. Your code does neither, so it assumes this is just a normal function unrelated to hooks or components.
Rename header to Header to fix this.

Related

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component

Hi I am building a spotify clone and at some point the guide tells me to add{Icon && <Icon className="sidebarOption__icon" />} to the SidebarOption file. However when I type the command my local host app disapears and I see a blank background. A lot of people have this problem in the comment section but no solution has been found. <Icon /> is enough to make the app go blank and give me the error, Warning: Invalid hook call. Hooks can only be called inside of the body of a function component along with many more. The purpose is to introduce icons in the app.
The code for SidebarOption.js is:
import React from 'react'
import "./SidebarOption.css";
function SidebarOptions({title, Icon}) {
return (
<div className="sidebarOption">
{Icon && <Icon className="sidebarOption__icon" />}
{Icon ? <h4>{title}</h4> : <p>{title}</p> }
</div>
)
}
export default SidebarOptions
and of Sidebar.js is:
import React from 'react'
import './Sidebar.css'
import SidebarOption from './SidebarOption'
import HomeIcon from '#mui/icons-material/Home';
import SearchIcon from '#mui/icons-material/Search';
import LibraryMusicIcon from '#mui/icons-material/LibraryMusic';
function Sidebar() {
return (
<div className="sidebar">
<img
className="siderbar__logo"
src="https://getheavy.com/wp-content/uploads/2019/12/spotify2019-830x350.jpg"
alt=""
/>
<SidebarOption Icon={HomeIcon} title="Home"/>
<SidebarOption Icon={SearchIcon} title="Search" />
<SidebarOption Icon={LibraryMusicIcon} title="Your Library" />
</div>
)
}
export default Sidebar
Thank your for the help in advance!!
I saw a solution from the comment section where the user said to delete your node_modules folder and reinstall everything using npm install.

make a code preview for documentation with Reactjs

I'm trying to create a component who display source's code passed as props to write documentation of a library i work on with Docusaurus. Like html <code> or exactly like this (the blue part) :
https://mui.com/components/radio-buttons/
This is a simplified code
import React from 'react';
export default function Preview({title, description, component, code, rawComponent}) {
return (
<div>
<div><h1>{title}</h1></div>
<div>{description}</div>
<div>{component}</div>
<details>
<summary>Source</summary>
<pre>
<code>{code}</code>
</pre>
</details>
</div>
);
}
PROBLEM : i can't found how to pass code as props ....
<Preview
title={'Quick start'}
description={'Yes, this really is all you need to get started, as you can see in this live and interactive demo:'}
component={<HomepageFeatures />}
code={
`
import * as React from 'react';
import ReactDOM from 'react-dom';
import HomepageFeatures from 'newlib';
function App() {
return <HomepageFeatures />;
}
`}
/>
this also doesn't work
<Preview
title={'Quick start'}
description={'Yes, this really is all you need to get started, as you can see in this live and interactive demo:'}
component={<HomepageFeatures />}
code={
```
import * as React from 'react';
import ReactDOM from 'react-dom';
import HomepageFeatures from 'newlib';
function App() {
return <HomepageFeatures />;
}
```
}
/>
How to pass the code block ???
EDIT : a jsfildle https://jsfiddle.net/2pnc4htm/
it's work in pure reactJS, so it's Docusaurus who mess up ...
Thank you for reading
I believe the issue is that the curly braces are not required for the props. This only needs to be done for the in-line style of a component.
More information can be found here https://docusaurus.io/docs/next/markdown-features/react (in their examples they don’t use curly braces unless for the style)

React - loading Lightbox component into another component

I found a React lightbox example here. I am trying to make slight modifications to it and one of those modifications is that I want to include it in another component. I attempted to do that by changing render(<App />, document.getElementById('app')); to export default App and then importing it into my component. But when I do that I get Cannot read property '0' of undefined Here's how I am importing it:
import React from "react";
import LB from "./LB";
import "./styles.css";
export default function App() {
return <LB />;
}
Here's my attempt
<div>
<div onClick={this.openLightbox}>Click Me</div>
<Lightbox
views={photos}
onClose={this.closeLightbox}
onClickPrev={this.gotoPrevious}
onClickNext={this.gotoNext}
currentImage={this.state.currentImage}
isOpen={this.state.lightboxIsOpen}
/>
</div>
You were passing incorrect prop. Never rely on some dubious examples, always refer to the docs. "images" should be "views"

react-router connected to redux : works with links but only the URL change when dispatching push

I'm trying to programmatically push an URL to navigate with react-router, redux, and connected-react-router
When clicking on a <Link /> button, it's working great, the URL is changing and the route too.
But when using a dispatch(push(url)), the URL only change and the content is not updated
I've made a minimal example here.
Any help would be really grateful,
Thanks
A lot of anti-pattern code, poor application structured, and mixing of packages is holding your application back.
I rewrote it entirely, here's what I've done:
Reconfigured your application folder's structure to be standard.
Don't mix Router (BrowserRouter) with ConnectedRouter.
Don't place all of your components within the App.js file.
Since the Header is always mounted, you don't need redux, instead you can just use withRouter (it exposes route props to the component).
Your rootReducer is missing a reducer, so I added a dummyReducer that just returns state.
Stick to Link or this.props.history when navigating. For this example, there's no need to use both. Also, you don't need to use ConnectedRouter's push function, because the history is passed as a prop when using withRouter.
Side note: If you want the Header to be a "router" where all route changes pass through here, then you'll need to create an action and a reducer that passes a string and stores it to the redux's store. The Header is then connected to the redux store and updates the route when this string has changed.
Working example: https://codesandbox.io/s/526p7kjqq4
components/Header.js
import React, { PureComponent, Fragment } from "react";
import { withRouter } from "react-router-dom";
class Header extends PureComponent {
goTo = route => {
this.props.history.push(route);
};
render = () => (
<Fragment>
<ul>
<li>
<button onClick={() => this.goTo("/")}> Announcements </button>
</li>
<li>
<button onClick={() => this.goTo("/shopping")}> Shopping </button>
</li>
</ul>
<div>
<button onClick={() => this.goTo("/shopping")}>
Click here to go shopping ! (if you can...)
</button>
</div>
</Fragment>
);
}
export default withRouter(Header);
routes/index.js
import React from "react";
import { Switch, Route } from "react-router-dom";
import Announcements from "../components/annoucements";
import Shopping from "../components/shopping";
export default () => (
<div style={{ padding: "150px" }}>
<Switch>
<Route exact path="/" component={Announcements} />
<Route path="/shopping" component={Shopping} />
</Switch>
</div>
);
components/App.js
import React, { Fragment } from "react";
import Routes from "../routes";
import Header from "./Header";
export default () => (
<Fragment>
<Header />
<Routes />
</Fragment>
);
Here is what you're trying to accomplish: https://codesandbox.io/s/8nmp95y8r2
However, I DO NOT recommend this as it's a bit unnecessary, when history is either already passed as a prop from the Route or can be exposed when using withRouter. According to the Redux docs, it's not recommended either. And instead to either use Link or pass the history prop to the redux action creator instead of programmatic navigation through redux state.
containers/Header.js
import React, { PureComponent, Fragment } from "react";
import { connect } from "react-redux";
import { push } from "connected-react-router";
class Header extends PureComponent {
goTo = route => this.props.push(route); // this is equivalent to this.props.dispatch(push(route)) -- I'm just appending dispatch to the push function in the connect function below
render = () => (
<Fragment>
<ul>
<li>
<button onClick={() => this.goTo("/")}> Announcements </button>
</li>
<li>
<button onClick={() => this.goTo("/shopping")}> Shopping </button>
</li>
</ul>
<div>
<button onClick={() => this.goTo("/shopping")}>
Click here to go shopping ! (if you can...)
</button>
</div>
</Fragment>
);
}
export default connect(
null,
{ push }
)(Header);
After reading the complete thread react-router-redux's push() not rendering new route, I came across this solution you need to use Router with passing down history as prop down to your app and don't use create from multiple files just import it from a common file.
Here is the working codesandbox: push rendering the new route

How To create a Global Component like Toast in React And Refer it in any other component?

I am trying to create a App using React. I want to add a toast component globally to the app so that it can be referred by other component for displaying custom messages.
I want to add the toast in the following hierarchy:
ReactDOM.render(
<BrowserRouter>
<section>
<App />
<Toast />
</section>
</BrowserRouter>
And refer the Toast Component inside the App. How can I implement it?
you should install package
https://www.npmjs.com/package/react-toastify
and then add import and add
<ToastContainer />
in your header or some component like sidebar which is being used at every page.
You can now show toast messages on any page by just
toast.error("this is toast error");
First you need to import the ToastContainer and the CSS file :
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
and then inside the App.js add the ToastContainer on top :
<React.Fragment>
<ToastContainer />
<NavBar ... />
....
</React.Fragment>
And then you can use the toast popups in any of your components, classes and functions by importing Toast:
import { toast } from "react-toastify";
and then using it with toast() or toast.error() or toast.info() etc methods
toast("Wrong email or Password");
...
toast.error("Some kind of Error");
Hope it helps !
I've tried that approach (including ToastContainer component), but the toast.something didn't fire the event through the Toast component. The solution I've implemented was creating a function that mimics a component behavior, and instead of passing conditionals through props, pass arguments. Here's an example:
import React from "react";
import { toast } from "react-toastify";
const Toast = (message, type) => {
switch (type) {
case "success":
return toast.success(
<div>
<p>{message}</p>
</div>
);
case "error":
return toast.error(
<div>
<p>{message}</p>
</div>
);
case "warning":
return toast.warning(
<div>
<p>{message}</p>
</div>
);
default:
return toast.warning(
<div>
<p>Toast not defined...</p>
</div>
);
}
};
export default Toast;
Somewhere in the component:
Toast('Action successfully executed!', 'success');
You can pass the Toast component to App as a prop.
But this is probably not what you should do. I assume you want the Toast component to be triggered by various things other components can do. You would do this with state. Make Toast a function of state, and let other components modify state. You can do this with plane old setState, or use Redux. Though the author of Redux would tell you to just use setState.
Also because it is React there are already probably 7 libraries for doing this. This one looks promising.
Install toastify package from npm import it to your program and add the following to your program
<ToastContainer/>
You may also be interested in react-toastify so take a look at that.

Resources