How to use if else condition with variable in Reactjs - javascript

I am working in Reactjs. Right now I am getting the current url/hostname. Now I want to use this URL with an if-else condition, which means I just want if url="/"(home page) then the first header should display otherwise second word should display. In other words, I want to know how we can use if-else condition with dynamic variable?
Here is my current code
import { useRouter } from 'next/router'
const Header = () => {
const router = useRouter();
const url =router.asPath;
return (
<>
<div>
//need to use if else condition based on "url" variable
</div>
</>
)

You can use ternary operators there to render based on a condition, like this:
import { useRouter } from 'next/router'
const Header = () => {
const router = useRouter();
const url = router.asPath;
return (
<>
<div>
{url === "something" ? <Foo /> : <Bar />}
</div>
</>
)
}

import { useRouter } from 'next/router'
const Header = () => {
const router = useRouter();
const url = router.asPath;
return (
<>
<div>
{url === "smth" ? <First /> : <Second />}
</div>
</>
)
}
return (
<>
<div>
{url === "smth" && <First />}
{url === "smth" && <Second />}
</div>
</>
)
}
You use both methods

Related

how to change child component state in reactjs

I came across the following problem: I need to use another component's function inside a component:
header.js
export default function Header() {
const [showModalLogin ,setShowModalLogin] = useState(false);
return(
<>
<span>Hi, <Link onClick={() =>{ setShowModalLogin(true)}}>login</Link> </span>
{showModalLogin ? <LoginModal setShowModalLogin={setShowModalLogin}/> : ''}
</>
);
}
home.js
import Header from '../../components/header/header';
export default function Home() {
return (
<>
<Header />
<Link onClick={() =>{ setShowModalLogin(true)}}>open login</Link>
</>
}
How do I do in home.js to call the setShowModalLogin function that is in header.js ? I'm trying to use the context api too, but I still can't solve it.
You can just place useState in Header component and pass setShowModalLogin as props:
import Header from '../../components/header/header';
export default function Home() {
const [isShowModalLogin ,setShowModalLogin] = useState(false);
return (
<>
<Header isShowModalLogin={isShowModalLogin} setShowModalLogin={setShowModalLogin} />
<Link onClick={() => setShowModalLogin(true)}>open login</Link>
</>
}
export default function Header({ isShowModalLogin, setShowModalLogin }) {
return(
<>
<span>Hi, <Link onClick={() => setShowModalLogin(true)}>login</Link> </span>
{isShowModalLogin ? <LoginModal setShowModalLogin={setShowModalLogin}/> : ''}
</>
);
}
Then you can do it in this way:
Create Context
Save useState inside
Use it everywhere you need
export const YourContext = createContext();
export const YourProvider = ({ children }) => {
const [isShowModalLogin, setShowModalLogin] = useState(false);
const value = {
isShowModalLogin,
setShowModalLogin
};
return <YourContext.Provider value={value}>{children}</YourContext.Provider>;
}
// App.js
const App = () => {
return (
<YourProvider>
<AppContent />
</YourProvider>
)
}
So now you can use it like here:
import Header from '../../components/header/header';
export default function Home() {
const { isShowModalLogin, setShowModalLogin } = useContext(YourContext);
return (
<>
<Header isShowModalLogin={isShowModalLogin} setShowModalLogin={setShowModalLogin} />
<Link onClick={() => setShowModalLogin(true)}>open login</Link>
</>
}

The initial render of the useEffect is disturbing the values of the cryptos. What is the solution?

I want that the Input field acts as a search bar and shows me the typed cryptocurrencies but because of the initial render of the useEffect, the value of the cryptos is being set to undefined and because of this no crypto is being shown on the page. Please suggest any alternate way to implement this functionality and also How can I stop the useEffect to get render at the starting .
import { Card, Row, Col, Input, Typography } from 'antd'
import React from 'react'
import { Link } from 'react-router-dom'
import { useGetCryptosQuery } from '../services/CryptoApi'
import { useState, useEffect } from 'react'
import millify from 'millify'
import { filter } from 'htmlparser2/node_modules/domutils'
const Cryptocurrencies = ( props ) => {
const count = props.simplified ? 10 : 100;
const { data: cryptoList, isFetching } = useGetCryptosQuery( count )
const [cryptos, setCryptos] = useState( cryptoList?.data?.coins )
const [searchTerm, setSearchTerm] = useState( '' )
useEffect( () => {
const filteredData = cryptoList?.data?.coins.filter( ( coin ) => { coin.name.toLowerCase().includes( searchTerm.toLowerCase() ) } )
setCryptos( filteredData )
}, [searchTerm, cryptoList] )
console.log( cryptos )
if ( isFetching ) {
return "loading...";
}
return (
<div>
{
<>
<div>
<Input placeholder="Search Cryptocurrency" onChange={( e ) => setSearchTerm( e.target.value )} className="" />
</div>
<Row gutter={[32, 32]} className="crypto-card-container">
{cryptos?.map( ( currency ) => {
return (
<Col xs={24} sm={12} lg={6} className="crypto-card" key={currency.id}>
<Link to={`/ crypto / ${currency.id} `}>
<Card
title={`${currency.rank}.${currency.name} `}
extra={<img className="crypto-image" src={currency.iconUrl} />}
hoverable
>
<p>Price : ${millify( currency.price )}</p>
<p>Market Cap : {millify( currency.marketCap )}</p>
<p>Daily Change : {millify( currency.change )}%</p>
</Card>
</Link>
</Col>
)
} )}
</Row>
</>
}
</div>
)
}
export default Cryptocurrencies
Simply can add a conditional if statement to solve the issue.
Let's take a look at the useEffect, As you describe at the component did mount, the searchTerm is still an empty string. By adding a simple if statement to check the seatchTerm value, filteredData and setCryptos methods only works when searchTerm has a string with a minimum of one letter.
useEffect( () => {
if(searchTerm.length > 0) {
const filteredData = cryptoList?.data?.coins.filter((coin) => { coin.name.toLowerCase().includes(searchTerm.toLowerCase())})
setCryptos(filteredData)
}
}, [searchTerm, cryptoList] )

How can I use same prop in multiple functional components in react

This is my App.jsx:
import React from 'react';
import SoltM from './slot';
const App = ()=>{
return(
<>
<div>
<SlotM x="emoji1" y="emoji1" z="emoji1" />
<hr />
<SlotM x="emoji2" y="emoji3" z="emoji3" />
<hr />
<SlotM x="emoji3" y="emoji3" z="emoji3" />
<hr />
</div>
</>
)
}
export default App;
This is my SlotM.jsx component, in this, props are not displayed in True or False component.
import React from 'react';
const SlotM = (props) => {
return ( (props.x === props.y && props.y === props.z) )}
const True = (props) => {
let { x, y, z } = props
return (
<>
<div className="slot_inner">
<h1> {x} {y} {z} </h1>
<h1> This is Matching </h1>
</div>
</>
)
}
const False = (props) => {
let { x, y, z } = props
return (
<>
<div className="slot_inner">
<h1> {x} {y} {z} </h1>
<h1> This is not Matching. emoji1 </h1>
</div>
</>
)
}
export default SlotM;
This is my app.jsx
2:This is SlotM.jsx component in this props are not being displayed in True and False component
You can use spread operator like this:
<True {...props} /> <False {...props} />
I think you misunderstood sth. props.x === props.y && props.y === props.z) ) returns boolean value, not Function. How about this?
const SlotM = (props) => {
return (props.x === props.y && props.y === props.z) ? <TrueC {...props}/>: <FalseC {...props}/>
}
const TrueC = (props) => {
...
const FalseC = (props) => {
...

Onclick Button is not being called React

I have this component that processes a card and when you click it redirects you to a past route but your OnClick is not working. I wonder if I could be going wrong
function Characters({
characters,
getAllCharacters,
filterCharacters,
}) {
const history = useHistory();
useEffect(() => {
characters.length === 0 && getAllCharacters();
}, [getAllCharacters]);
return (
<Fragment>
<Header />
<Search characters={characters} />
{ inputCharacters !== "" && filterCharacters.length > 0 ? (
<ListContainer>
{filterCharacters.map((characters) => (
<CardItem
onClick={() => {
history.push(`/characters/${characters.id}`, {
params: { characters },
});
}}
key={characters.id}
name={characters.name}
images={
characters.thumbnail.path + "." + characters.thumbnail.extension
}
/>
)}
</ListContainer>
Component CardItem:
export default function CardItem(props) {
return (
<Container url={props.images}>
<Content>
<p>{props.name}</p>
</Content>
</Container>
);
}
Because you are not using onClick in the CardItem. You just update like this:
<p onClick={props.onClick}>{props.name}</p>
If Container or Content support onClick, you cant put onClick={props.onClick} in this component like a prop

React Router Redirect to component not redirecting

I need a simple redirect to a component but its not working not sure why. This is the code:
const HomePage = () => {
const [videos, setVideos] = useState([]);
const videoClicked = (video) => {
return <Redirect to='/video' />
}
if(videos === []){
return <div>Loading ...</div>
}
return (
<div>
{videos.map(video => (
<div onClick={() => videoClicked(video)}>
<VideoThumbnail video={video} />
</div>
))}
</div>
)
}
export default HomePage
I have a useEffect in my HomePage function that I didnt include in this snippet that gives videos values. It works and when I onClick the div it calls videoClicked but the redirect doesnt work.
This is my router:
const App = () => {
return (
<HashRouter>
<Switch>
<Route exact path="/video" component={VideoPage} />
<Route path="/" component={HomePage} />
</Switch>
</HashRouter>
)
}
Also when I get this working is it possible to redirect to component and pass props thru it instead of just passing a string in the to tag.
You can have a new state and redirect based on that:
const HomePage = () => {
const [videos, setVideos] = useState([]);
const [clicked, setClicked] = useState(false);
const videoClicked = (video) => {
setClicked(true);
// return <Redirect to='/video' />
}
if (videos === []) {
return <div>Loading ...</div>
}
return (
clicked ? <Redirect to={{
pathname: '/video',
state: { someData: 'test' }
}} /> : (
<div>
{videos.map(video => (
<div onClick={() => videoClicked(video)}>
<VideoThumbnail video={video} />
</div>
))}
</div>
)
)
}
export default HomePage
and you can use props.location.state.someData in the component you're redirected to.
you can consider using History HTML5 instead :) simple and straightforward

Categories

Resources