How to do conditional check twice in React component - javascript

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>
);
};

Related

Creating generic components in React Javascript

I'm trying to build a React select component that can support multiple different child component types.
I'd like to do something like this:
export const GenericSelect = (props) => {
const { component, items } = props;
return <>{items && items.map((item, index) => <component id={items.id} name={item.name} />)}</>;
};
And then be able to use it like:
<GenericSelect component={NonGenericCard} items={items} />
Where NonGenericCard supports a fixed set of properties (e.g., id, name), which will be populated from values in the items object.
I tried this, but it doesn't seem like it can create the <component/> at run-time.
Is this possible in Javascript? If so, how can it be accomplished?
In JSX, lower-case tag names are considered to be HTML tags. So you should use Component instead of component.
Also id should be item.id instead of items.id and you should give each element a key.
export const GenericSelect = (props) => {
const { Component, items } = props;
return (
<>
{items &&
items.map((item, index) => (
<Component key={item.id} id={item.id} name={item.name} />
))}
</>
);
};
<GenericSelect Component={NonGenericCard} items={items} />
https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized

In react, how can I add multiple ref to the element using map?

export default function RenderPages({storage, setStorage, state, setState}){
const elRefs=[]
for(let i=0; i<storage[state.currentFolderId][state.currentFileId].content.length; i++){
elRefs.push(useRef())
}
return (
<>
{
renderable
?<div className="writing">
{storage[state.currentFolderId][state.currentFileId].content.map((page, index)=>
<div className='textarea'>
<textarea ref={elRefs[index]} placeholder='write here' value={page} id={"page"+index} onChange={(e)=>onChange(e, index)} rows={rows} cols={cols}></textarea>
</div>)}
</div>
: <></>
}
</>
)
}
I want to attach multiple ref to random number of "textarea" element. the number of element would be determined by the variable, "storage", which is given as props. I got error with above code. Help me please.
you don't need to use for loop to push the elements in ref, you already use map in return you can push textarea elements using ref like this way as you can see the below code, I hope this works. thanks
import { useRef } from "react";
export default function RenderPages({storage, setStorage, state, setState}) {
const elRefs = useRef([]);
return (
<>
{renderable ? (
<div className="writing">
{storage[state.currentFolderId][state.currentFileId].content.map((page, index) => (
<div className="textarea">
<textarea
ref={ref => {
elRefs.current[index] = ref
}}
placeholder="write here"
value={page}
id={'page' + index}
onChange={e => onChange(e, index)}
rows={rows}
cols={cols}></textarea>
</div>
))}
</div>
) : (
<></>
)}
</>
);
}
const myRefs = useRef([])
ref={ref => myRefs.current[index] = ref} // <--- Right syntax
Using one ref with multiple current elements is enough
Shouldn't (and don't need) call hook in a loop, in this case, it's invalid https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

how do you pass down an object containing props

after getting all mixed up with state, i am now trying to restructure my app in a way that might be more reflective of best practices (not sure if this is the way, advice is welcome.)
so, i have my main page, which holds 3 states: viewer,buyside,sellside
there are also three different components, one for each of those states.
i want to be able to pass the props down from the main page, through those components, to their children (i've read this is the best approach??)
main page:
//we have 3 states for the website: viewer,buyside customer, sellside customer
const [visitorType, setVisitorType] = useState('viewer');
if (visitorType == 'viewer') {
return(
<div>
<Viewer visitortype='viewer' setvisitor={()=>setVisitorType()}/>
</div>
)}
else if (visitorType =='buyside') {
return(
<div>
<Buyside visitortype='buyside' setvisitor={()=>setVisitorType()}/>
</div>
)}
else if (visitorType =='sellside') {
return(
<div>
<Sellside visitortype='sellside' setvisitor={()=>setVisitorType()}/>
</div>
)}
};
what is the best way to pass down the main page props, so that i can bring them down to any grandchildren, along with the child props?
the viewer component -UPDATED-:
const MainView = (props) => {
return(
<>
<Navbar mainprops={{props}}/>
</>
)
};
export default MainView
i was previously just passing them individually, but realized it might be better to do so as one object...
UPDATE: point taken on the syntax, but i'm wondering how i can best pass the objects
nav component (grandchild)
const Navbar = (props) => {
const {mainprops} = props.mainprops;
if (mainprops.visitortype == 'viewer') {
return(
<>
<h1>viewer navbar</h1>
</>
)}
else if (mainprops.visitortype =='buyside') {
return(
<>
<h1>buyside navbar</h1>
</>
)}
else if (mainprops.visitortype =='sellside') {
return(
<>
<h1>sellside navbar</h1>
</>
)}
};
export default Navbar;
UPDATE 2 - this works, but not sure if it is the correct way, are these still considered object literals??
viewer component:
const MainView = (props) => {
const mainprops = {...props}
return(
<>
<Navbar mainprops={mainprops}/>
</>
)
};
export default MainView
navbar component
const Navbar = (props) => {
const mainprops = {...props.mainprops};
if (mainprops.visitortype == 'viewer') {
return(
<>
<h1>viewer navbar</h1>
</>
)}
else if (mainprops.visitortype =='buyside') {
return(
<>
<h1>buyside navbar</h1>
</>
)}
else if (mainprops.visitortype =='sellside') {
return(
<>
<h1>sellside navbar</h1>
</>
)}
};
export default Navbar;
if this is correct, then is this what #amir meant?
First there are certain rules for passing props:
You never ever pass literal object as props since it will not be the same every re-render and will cause the child component to re-render too (without any new info)
You don't need to do that
<Viewer visitortype='viewer' setvisitor={()=>setVisitorType()}/>
You can:
<Viewer visitortype='viewer' setvisitor={setVisitorType}/>
since it comes from useState react make sure the setVisitorType keeps the same reference
And now for you error, you almost correct you just did a js syntax error
you should write it like this:
const MainView = (props) => {
return(
<>
<Navbar mainobj={{
visitortype:props.visitortype,
setvisitor:props.setvisitor
}}
/>
</>
)
};
export default MainView
But again you never send literal object as props
I would keep it inside a ref or state (depend if the visitor state will be change)

React nested rendering

I have an object containing several arrays like:
const Items = {
Deserts: [{name:cookies}, {name:chocolate}],
Fruits: [{name:apple}, {name:orange}]
...
}
I want to render it as:
<title>Deserts</title>
Cookies
Chocolate
<title>Fruits</title>
Apple
Orange
So first I render the type:
return <Grid>
{Object.keys(Items).map(type => {
return <Box key={type}>
{type} // <== this would be the title, Fruits or whatever
{this.createCard(Items[type])}
</Box>
})}
</Grid>
Then I want to add the content of each type:
createCard = (items) => {
return <Box>
{items.forEach(item => {
return <div>{item.name}</div>
})}
</Box>
}
Content is not returned, it works fine if instead of a forEach loop I just add some predefined content.
The forEach method only iterates over all items but does not return anything. Instead, what you want to use is a map.
Also, make sure you wrap your return value when it extends more than one line:
createCard = (items) => {
return (<Box>
{items.map(item => {
return <div>{item.name}</div>
})}
</Box>);
}
If you don't do that it works as if a semicolon was introduced after the first line. So, in reality, your current code is equivalent to:
createCard = (items) => {
return <Box>;
// The code below will never be executed!
{items.forEach(item => {
return <div>{item.name}</div>
})}
</Box>
}
When returning an element you need to wrap it in parentheses, ( ) and I generally use map instead of forEach.
const createCard = items => {
return (
<Box>
{items.map(item => {
return ( <div>{item.name}</div> )
})}
</Box>
)
}
I believe you can also nix the curly braces if the function doesn't need any logic.
const createCard = items => (
<Box>
{items.map(item => {
return ( <div>{item.name}</div> )
})}
</Box>
)
-- Edit --
Now that I'm reading back over your question a much cleaner way to approach this would be to declare the component function outside of your class like
class Grid extends react.Component {
render(){
return (
<Box>
<CreateCard props={ item }/>
</Box
)
}
}
const CreateCard = props => (
<Box>
{props.items.map(item => {
return ( <div>{item.name}</div> )
})}
</Box>
)

DRY jsx render method

I wonder if it is a better way to DRY this code, have you guys any ideas?
The props are the same, just the component change...
render() {
const { input: { value, onChange }, callback, async, ...rest } = this.props;
if (async) {
return (
<Select.Async
onChange={(val) => {
onChange(val);
callback(val);
}}
value={value}
{...rest}
/>
);
}
return (
<Select
onChange={(val) => {
onChange(val);
callback(val);
}}
value={value}
{...rest}
/>
);
}
With:
let createElement = function(Component) {
return (
<Component onChange={(val) => {
onChange(val);
callback(val);
}}
value={value}
{...rest}
/>
);
};
you can do
let selectAsync = createElement(Select.Async);
let select = createElement(Select);
You can render them in the jsx part with {{select}} and {{selectAsync}}
P.S.: I didnt test this directly, but did something very similar a few days ago, so this approach should work. Note that Component must start with a capital letter.

Categories

Resources