I am trying to render a component based on the condition.
exceptPath: ['home', 'person']
pathName = 'test'
return (
<React.Fragment>
{this.state.exceptPathNames.map((exceptPathName) => {
console.log(exceptPathName);
pathName === exceptPathName ? console.log('test') : <LinkGridLayout />;
})}
</React.Fragment>
);
If pathName is not "home" or "person" I want to return <LinkGridLayout /> else do not return anything.
If all you want to do is render a LinkGridLayout component for any pathName value that is not "home" or "person" (or any value in excludePath really) then I'd suggest the following refactor to check that no elements in the array equal the pathName, and if so, conditionally render LinkGridLayout.
Example:
exceptPath: ['home', 'person']
return (
<>
{!exceptPath.some((exceptPathName) => pathName === exceptPathName) && (
<LinkGridLayout />
)}
</>
);
or
return (
<>
{exceptPath.every((exceptPathName) => pathName !== exceptPathName) && (
<LinkGridLayout />
)}
</>
);
Related
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
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
my state variable contains an array of objects(where is each object contains username,user_DP,imageUrl, caption) which is to be rendered but while using map() to render gives an error that I am unable to resolve.
example of state variable :
this.state = {
route: 'signin',
postDetails: [...]
};
and my render() looks like
render(){
const {route, postDetails} = this.state;
return (
<div className="App">
{
route === 'home' ?
<Navbar/>
{
postDetails.map((post,index)=>{
return(<Post
key = {index}
username = {post.username}
user_DP = {post.user_DP}
imageUrl = {post.imageUrl}
caption = {post.caption}
/>);
})
}
:
(
route === 'signin'?
<Signin onRouteChange = {this.onRouteChange}/>
:
<Signup onRouteChange = {this.onRouteChange}/>
)
}
</div>
);
}
I am getting an error like this
Syntax error: Unexpected token, expected ":" (44:13)
42 | route === 'home' ?
43 | <Navbar/>
> 44 | {
| ^
45 | postDetails.map((post,index)=>{
46 | return(<Post
47 | key = {index}
please help in removing this error it will greatly help me.
Your <Navbar /> and map() with <Post>s must be within a single node. You might use React.Fragment or wrap them in a <div> if that doesn't break your design:
The React.Fragment component lets you return multiple elements in a render() method without creating an additional DOM element.
function render() {
const { route, postDetails } = this.state;
return (
<div className="App">
{route === "home" ? (
<> {/* <- shorthand for <React.Fragment> */}
<Navbar />
{postDetails.map((post, index) => {
return (
<Post
key={index}
username={post.username}
user_DP={post.user_DP}
imageUrl={post.imageUrl}
caption={post.caption}
/>
);
})}
</> {/* <- shorthand for </React.Fragment> */}
) : route === "signin" ? (
<Signin onRouteChange={this.onRouteChange} />
) : (
<Signup onRouteChange={this.onRouteChange} />
)}
</div>
);
}
I have a React component as shown. I am passing prop hasItems and based on this boolean value, i am showing PaymentMessage Component or showing AddItemsMessage component.
export const PayComponent = ({
hasItems
}: props) => {
return (
<Wrapper>
{hasItems ? (
<PaymentMessage />
) : (
<AddItemsMessage />
)}
<Alerts
errors={errors}
/>
</Wrapper>
);
};
This works well. Now, i need to pass another prop (paymentError). So based on this, i modify the JSX as below. I will highlight the parts i am adding by using comment section so it becomes easy to see.
export const PayComponent = ({
hasItems,
paymentError //-----> added this
}: props) => {
return (
<Wrapper>
{!paymentError ? ( //----> added this. This line of code errors out
{hasItems ? (
<PaymentMessage />
) : (
<AddItemsMessage />
)}
):( //-----> added this
<Alerts
errors={errors}
/>
) //-----> added this
</Wrapper>
);
};
Basically, i am taking one more input prop and modifying the way my JSX should look. But in this case, i am not able to add one boolean comparison one after the error. How do i make it working in this case. Any suggestions please ???
I recommend you to create a function to handle this behavior. It's easier to read and to mantain
export const PayComponent = ({
hasItems,
paymentError
}: props) => {
const RenderMessage = () => {
if (hasItems) {
if (paymentError) {
return <PaymentMessage />
}
return <AddItemsMessage />
}
return <Alerts errors={errors}/>
};
return (
<Wrapper>
<RenderMessage />
</Wrapper>
);
};
I have a component that renders some data coming from an array. I need to filter that array depending on a condition. I don't know if filter the array is the proper way, or just to remove the item I don't need from that array.
The component looks like this:
const PassengerCardBasedOnRoute = ({
passengerCardId,
isAddToMyPassengersSuccess,
unassignedDropOffPassengers
}) => {
const filteredData = filterByParam =>
filterByParam.filter(obj =>
Object.keys(obj).some(key =>
String(obj[key])
.toLowerCase()
.includes(searchParam.toLowerCase()),
),
);
const componentToRenderBasedOnParams = info => (
<View key={info.id}>
{isAddToMyPassengersSuccess && info.id === passengerCardId && (
<PassengersAdded name={info.name} id={info.id} />
)}
<PassengersInfo
id={info.id}
name={info.name}
/>
</View>
);
const showFeedbackIfNoLength = data => {
if (size(filteredData(data))) {
filteredData(data).map(info => componentToRenderBasedOnParams(info));
}
};
return (
<>
<OptionsModal>{<AllPassengersOptionsModal />}</OptionsModal>
<View>
{unassignedDropOffPassengers && showFeedbackIfNoLength(unassignedDropOffPassengers)}
</View>
</>
);
};
The array of data I am attempting to work on is this unassignedDropOffPassengers. Which you may see above.
And the key function to work on is this:
const componentToRenderBasedOnParams = info => (
<View key={info.id}>
{isAddToMyPassengersSuccess && info.id === passengerCardId && (
<PassengersAdded name={info.name} id={info.id} />
)}
<PassengersInfo
id={info.id}
name={info.name}
/>
</View>
);
The valid condition is this:
{isAddToMyPassengersSuccess && info.id === passengerCardId && (
<PassengersAdded name={info.name} id={info.id} />
)}
What I should should do is that when the condition above is met, I should remove the item from unassignedDropOffPassengers. Or just filter it like here where I am applying a filter:
const filteredData = filterByParam =>
filterByParam.filter(obj =>
Object.keys(obj).some(key =>
String(obj[key])
.toLowerCase()
.includes(searchParam.toLowerCase()),
),
);
What I want to know is how to achieve it/adapt it with my code. Based on the condition I mentioned above isAddToMyPassengersSuccess && info.id === passengerCardId.
The item in the array that I need to omit, is the one matching passengerCardId.
So any ideas?
EDIT:
I am using lodash btw.