Restructure repetitive component to get rendered within a map function - javascript

While I wrote my component as much DRY as I could, I wonder if there is a better way to render ConnectButton through a map function that takes [linkedIn, twitter, researchGate] as an array. I tried different things, but that's as good as I could get it. (I simplified the code a bit to the relevant. The original version is by a lot longer.)
const Component = () => {
const ConnectButton = ({ icon, title }) => (
<MenuItem>
<ListItemIcon className={classes.listItemIcon}>
<Icon className={classes.connectIcon} icon={icon} />
</ListItemIcon>
<ListItemText primary={title} />
</MenuItem>
);
const renderConnectMenu = () => {
if (!profileInfo) {
return;
}
const linkedIn = profileInfo.linkedIn;
const twitter = profileInfo.twitter;
const researchGate = profileInfo.researchGate;
return (
<div>
{linkedIn && <ConnectButton icon={faLinkedin} title="LinkedIn" />}
{twitter && <ConnectButton icon={faTwitter} title="Twitter" />}
{researchGate && (
<ConnectButton icon={faResearchgate} title="Research Gate" />
)}
</div>
);
};
render(
<>
[...]
{renderConnectMenu()}
[...]
</>
);
};

There are 3 properties that define the rendering of a button: a field from profileInfo, icon and title. So we will need an array of objects with these properties in order to render them with .map.
I am not sure what kind of date the profileInfo fields hold so I named the property as shouldRender based on its usage.
const renderConnectMenu = () => {
if (!profileInfo) {
return;
}
const buttons = [
{
shouldRender: profileInfo.linkedIn,
icon: faLinkedin,
title: 'LinkedIn',
},
{
shouldRender: profileInfo.twitter,
icon: faLinkedin,
title: 'Twitter',
},
{
shouldRender: profileInfo.researchGate,
icon: faLinkedin,
title: 'Research Gate',
},
];
return (
<div>
{buttons.map(
(button) =>
button.shouldRender && (
<ConnectButton
key={button.title}
icon={button.icon}
title={button.title}
/>
),
)}
</div>
);
};
It might look a bit weird when you have a few items to render. So I wouldn't recommend this approach if there are just 2-3 items unless there is a possibility of extending the list. It's okay to keep it as it is now.

Related

React Native/API - onPress returns all links in API instead of the link relevant to the item being pressed

Apologies, couldn't figure out a straightforward way to title this, so thanks in advance.
I am tasked with creating a page of links supplied by an API I made that connects to a CMS. The screen gathers the below data to be viewed on the screen:
Title,
Content
These items, along with a URL live within a "Resource". The URL is not visible to the user, but it is grouped with its own Title and Content.
Currently things show correctly on the screen, but when trying to connect the URL to the Resource, I'm unable to have the page navigate correctly. When I console.log(thing-I'm-returning), it sends me back all URLs for all Resources, and if the private browser opens to a web page, it might open to any in the list. This happens when I press any of the Resources.
Code below (first time posting, I'm fully desperate. Let me know if this looks like trash and I'll correct however is ideal).
const { resourceData } = useResourceContent(binding);
const resourceList = resourceData?.Resources?.map((r, i) => ({
id: i.toString(),
title: r.Title,
url: r.Url,
content: r.Content,
}));
const resourceDetails = resourceData?.Resources;
const { openUrl } = useWebBrowser();
const { resourceData } = useResourceContent(binding);
const resourceDetails = resourceData?.Resources;
const urlList = [];
const handleOpenSite = () => {
resourceDetails?.map((r, i) =>
{if (resourceDetails !== undefined && resourceDetails) {
urlList.push(r.Url);
}
console.log(urlList[i]); //let's say there are 2 resources, each with their own website. This will return both websites no matter what resource I select
//the below is required, as a private browser is required
return openUrl(urlList[i]);
});
};
API looks something like:
[{"Content": "Test. ", "Url": "https://instagram.com", "Title": "blah blah blah"},
{{"Content": "Test2.", "Url": "https://google.com.com", "Title": "blah blah blah"},]
Here's the View, though I'm unsure if it's necessary here.
<View>
<ResourceNavigationList
onPress={handleOpenSite}
small
listItems={resourceList}
backgroundColor="transparent"
/>
</View>
And here's the ResourceNavigationList component, which is likely the issue since it's a little bit nonsense.:
const ResourceNavigationList = ({
listItems,
backgroundColor,
small,
reverse,
onPress,
}) => {
const { ct } = useCountryTranslation();
const colorScheme = useColorScheme();
const bgColor = backgroundColor || Colors[colorScheme].altBackground;
const { openUrl } = useWebBrowser();
const renderItem = ({ item, rUrl }) => {
const handleOnPress = () => {
if (item) {
openUrl(rUrl).toString();
console.log("WHY AREN'T YOU OPENING?");
}
};
return (
<ResourceNavigationListItem
key={key}
reverse={reverse}
small={small}
item={item}
// url={rUrl}
onPress={onPress}
/>
);
};
return (
<FlatList
renderItem={renderItem}
data={listItems}
keyExtractor={(item) => item.id}
style={{
paddingVertical: 20,
backgroundColor: bgColor,
}}
/>
);
};
ResourceNavigationList.propTypes = {
listItems: PropTypes.array.isRequired,
backgroundColor: PropTypes.string,
small: PropTypes.bool,
reverse: PropTypes.bool,
onPress: PropTypes.func,
};
export default ResourceNavigationList;
Finally, here's the ResourceNavigationListItem
const ResourceNavigationListItem = ({ item, onPress, style, small }) => {
const styles = StyleSheet.create({
//styling is here, but leaving it off because it isn't relevant and took up a lot of space
});
return (
<TouchableOpacity onPress={onPress} style={[styles.item, style]}>
<View style={styles.title}>
<Icon style={styles.linkArrow} size={16} icon={faExternalLink} />
</View>
<View style={styles.title}>
<Text style={styles.titleText}>
{item.title ? decode(item.title) : item.title}
</Text>
</View>
<View style={styles.title}>
<Text style={styles.titleText}>
{item.content ? decode(item.content) : item.content}
</Text>
</View>
</TouchableOpacity>
);
};
ResourceNavigationListItem.propTypes = {
item: PropTypes.shape({
icon: PropTypes.object,
title: PropTypes.string,
content: PropTypes.string,
}).isRequired,
onPress: PropTypes.func,
style: PropTypes.object,
small: PropTypes.bool,
};
export default ResourceNavigationListItem;
Thanks so very much.
I've tried mapping and for-looping. I've tried applying the mapping directly to the component. These have gleaned me the most success. Most everything else I've tried didn't return anything at all, or returned everything many times.
I've been struggling for a few days and have found lots of solutions similar to my problem within stackoverflow, but nothing fully relevant/recent (I'm fairly newb with regard to backend tingz). If y'all happen upon something I missed, please be kind, and if you'd be down to help me, I'd be so very grateful.
I took a look and I think this has to do with confusion regarding the props hierarchy within your example.
Right now you are passing onPress down from the parent of ResourceNavigationList:
Parent > onPress
ResourceNavigationList
ResourceNavigationListItem
While there is nothing inherently incorrect about the parent owning the onPress function, you have everything you need to perform the desired onPress functionality within the ResourceNavigationList component. It looks like you were almost there with your handleOnPress function.
Based on the data contract you provided, it looks like you should be able to do this:
const ResourceNavigationList = ({
listItems,
backgroundColor,
small,
reverse,
onPress,
}) => {
const {
ct
} = useCountryTranslation();
const colorScheme = useColorScheme();
const bgColor = backgroundColor || Colors[colorScheme].altBackground;
const {
openUrl
} = useWebBrowser();
const renderItem = ({
item,
rUrl
}) => {
const handleOnPress = () => {
if (item && item ? .Url) {
openUrl(item ? .Url);
// If you do need to perform additional logic controlled
// by the parent component, you can add a quick line to
// execute the onPress function if it has been provided.
if (onPress) onPress(item);
}
};
return ( <
ResourceNavigationListItem key = {
key
}
reverse = {
reverse
}
small = {
small
}
item = {
item
}
onPress = {
onPress
}
/>
);
};
return ( <
FlatList renderItem = {
renderItem
}
data = {
listItems
}
keyExtractor = {
(item) => item.id
}
style = {
{
paddingVertical: 20,
backgroundColor: bgColor,
}
}
/>
);
};
ResourceNavigationList.propTypes = {
listItems: PropTypes.array.isRequired,
backgroundColor: PropTypes.string,
small: PropTypes.bool,
reverse: PropTypes.bool,
onPress: PropTypes.func,
};
export default ResourceNavigationList;

How to render AdMob banner in React Flatlist between items?

I have a React Native Flatlist that only re-renders when its data has changed.
I give it the following data (as prop):
const posts = [
{
...post1Data
},
{
...post2Data
},
{
...post3Data
},
{
...post4Data
},
{
...post5Data
},
]
And here is my FlatList renderItem:
const renderItem = useCallback(({ item, index }) => {
const { id, userData, images, dimensions, text } = item;
return (
<View
onLayout={(event) => {
itemHeights.current[index] = event.nativeEvent.layout.height;
}}
>
<Card
id={id}
cached={false}
userData={userData}
images={images}
dimensions={dimensions}
text={text}
/>
</View>
);
}, []);
How can I add an AdMob ad between the FlatList data with a probability of 5% without skiping any data in the posts array?
I have tried this:
const renderItem = useCallback(({ item, index }) => {
const { id, userData, images, dimensions, text } = item;
if (Math.random() < 0.05) return <Ad ... />
return (
<View
onLayout={(event) => {
itemHeights.current[index] = event.nativeEvent.layout.height;
}}
>
<Card
id={id}
cached={false}
userData={userData}
images={images}
dimensions={dimensions}
text={text}
/>
</View>
);
}, []);
But this causes 2 problems:
Some items from data are skipped (not returned)
When the flatlist re-renders (because of some of its props changes) the ads might disappear (there is a chance of 95%).
Any ideas? Should I render the ads randomly in the footer of my Card component like this?
const Card = memo ((props) => {
...
return (
<AuthorRow ... />
<Content ... />
<SocialRow ... /> {/* Interaction buttons */}
<AdRow />
)
}, (prevProps, nextProps) => { ... });
const AdRow = memo(() => {
return <Ad ... />
}, () => true);
I am not really sure about this option, it works but it could violate the admob regulations (?) (because I am adapting the ad to the layout of my card component)
I would appreciate any kind of guidance/help. Thank you.
I'm not sure if you ever found a solution to this problem, but I accomplished this by injecting "dummy" items into the data set, then wrapping the renderItem component with a component that switches based on the type of each item.
Assuming your flatlist is declared like this:
<FlatList data={getData()} renderItem={renderItem}/>
And your data set is loaded into a variable called sourceData that is tied to state. Let's assume one entry in your sourceData array looks like this. Note the 'type' field to act as a type discriminator:
{
"id": "d96dce3a-6034-47b8-aa45-52b8d2fdc32f",
"name": "Joe Smith",
"type": "person"
}
Then you could declare a function like this:
const getData = React.useCallback(() => {
let outData = [];
outData.push(...sourceData);
// Inject ads into array
for (let i = 4; i < outData.length; i += 5)
{
outData.splice(i, 0, {type:"ad"});
}
return outData;
}, [sourceData]);
... which will inject ads into the data array between every 4th item, beginning at the 5th item. (Since we're pushing new data into the array, i += 5 means an ad will be placed between every 4th item. And let i = 4 means our first ad will show after the 5th item in our list)
Finally, switch between item types when you render:
const renderItem = ({ item }) => (
item.type === 'ad'
?
<AdComponent ...props/>
:
<DataComponent ...props/>
);

Deleting list Item in react keep older items instead

I would like to delete selected item from list.
When I click on delete the right item get deleted from the list content but on UI I get always the list item fired.
I seems to keep track of JSX keys and show last values.
Here's a demo
const Holidays = (props) => {
console.log(props);
const [state, setState] = useState({ ...props });
useEffect(() => {
setState(props);
console.log(state);
}, []);
const addNewHoliday = () => {
const obj = { start: "12/12", end: "12/13" };
setState(update(state, { daysOffList: { $push: [obj] } }));
};
const deleteHoliday = (i) => {
const objects = state.daysOffList.filter((elm, index) => index != i);
console.log({ objects });
setState(update(state, { daysOffList: { $set: objects } }));
console.log(state.daysOffList);
};
return (
<>
<Header as="h1" content="Select Holidays" />
<Button
primary
icon={<AddIcon />}
text
content="Add new holidays"
onClick={() => addNewHoliday(state)}
/>
{state?.daysOffList?.map((elm, i) => {
console.log(elm.end);
return (
<Flex key={i.toString()} gap="gap.small">
<>
<Header as="h5" content="Start Date" />
<Datepicker
defaultSelectedDate={
new Date(`${elm.start}/${new Date().getFullYear()}`)
}
/>
</>
<>
<Header as="h5" content="End Date" />
<Datepicker
defaultSelectedDate={
new Date(`${elm.end}/${new Date().getFullYear()}`)
}
/>
</>
<Button
key={i.toString()}
primary
icon={<TrashCanIcon />}
text
onClick={() => deleteHoliday(i)}
/>
<span>{JSON.stringify(state.daysOffList)}</span>
</Flex>
);
})}
</>
);
};
export default Holidays;
Update
I'm trying to make a uniq id by adding timeStamp.
return (
<Flex key={`${JSON.stringify(elm)} ${Date.now()}`} gap="gap.small">
<>
<Header as="h5" content="Start Date" />
<Datepicker
defaultSelectedDate={
new Date(`${elm.start}/${new Date().getFullYear()}`)
}
/>
</>
<>
<Header as="h5" content="End Date" />
<Datepicker
defaultSelectedDate={
new Date(`${elm.end}/${new Date().getFullYear()}`)
}
/>
</>
<Button
primary
key={`${JSON.stringify(elm)} ${Date.now()}`}
icon={<TrashCanIcon />}
text
onClick={() => deleteHoliday(i)}
/>{" "}
</Flex>
);
I was hoping that the error disappear but still getting same behaviour
Issue
You are using the array index as the React key and you are mutating the underlying data array. When you click the second entry to delete it, the third element shifts forward to fill the gap and is now assigned the React key for the element just removed. React uses the key to help in reconciliation, if the key remains stable React bails on rerendering the UI.
You also can't console log state immediately after an enqueued state update and expect to see the updated state.
setState(update(state, { daysOffList: { $set: objects } }));
console.log(state.daysOffList);
React state updates are asynchronous and processed between render cycles. The above can, and will, only ever log the state value from the current render cycle, not the update enqueued for the next render cycle.
Solution
Use a GUID for each start/end data object. uuid is a fantastic package for this and has really good uniqueness guarantees and is incredibly simple to use.
import { v4 as uuidV4 } from 'uuid';
// generate unique id
uuidV4();
To specifically address the issues in your code:
Add id properties to your data
const daysOffList = [
{ id: uuidV4(), start: "12/12", end: "12/15" },
{ id: uuidV4(), start: "12/12", end: "12/17" },
{ id: uuidV4(), start: "12/12", end: "12/19" }
];
...
const addNewHoliday = () => {
const obj = {
id: uuidV4(),
start: "12/12",
end: "12/13",
};
setState(update(state, { daysOffList: { $push: [obj] } }));
};
Update handler to consume id to delete
const deleteHoliday = (id) => {
const objects = state.daysOffList.filter((elm) => elm.id !== id);
setState(update(state, { daysOffList: { $set: objects } }));
};
Use the element id property as the React key
{state.daysOffList?.map((elm, i) => {
return (
<Flex key={elm.id} gap="gap.small">
...
</Flex>
);
})}
Pass the element id to the delete handler
<Button
primary
icon={<TrashCanIcon />}
text
onClick={() => deleteHoliday(elm.id)}
/>
Use an useEffect React hook to log any state update
useEffect(() => {
console.log(state.daysOffList);
}, [state.daysOffList]);
Demo
Note: If you don't want (or can't) install additional 3rd-party dependencies then you can roll your own id generator. This will work in a pinch but you should really go for a real proven solution.
const genId = ((seed = 0) => () => seed++)();
genId(); // 0
genId(); // 1

How to send pass function as props to child component

I have a parent component and some child components and I want send function from parent to child and in child component call it.
parent:
const buttons = [
{
key: 'driveFormulaButton',
title: 'Drive Formula',
icon: faGitAlt,
type: 'primary',
function: (message) => {
console.log('fasf');
},
},
];
return (
<Child
buttons={buttons}
></Child>
);
Child Component:
const Child = (props) => {
return (
<Button size="small" type={props.buttons.type} onClick={props.buttons.function('test')}> //not work after set propery
<FontAwesomeIcon icon={props.buttons.icon} />
</Button>
);
});
You call the function instead of passing it an onClick callback and you should map the buttons array:
const Child = (props) => {
return props.buttons.map((prop) => (
<Button
key={prop.key}
size="small"
type={prop.type}
onClick={() => prop.function("test")}
>
<FontAwesomeIcon icon={prop.icon} />
</Button>
));
}
Your parent component needs to map through the children components:
Parent
function renderChildren() {
const buttons = []; // <--- populate this as in your OP
return buttons.map((button) => {
return (
<Button size="small" type={button.type} onClick={() => button.function('test')}>
<FontAwesomeIcon icon={button.icon} />
</Button>
)
})
}
return (
<>
{renderChildren()}
</>
);
Well you send an array of buttons as props to you single Child-Component. Then you try to access a single object of that array in the Button-Component. This cant work. Better map throught you button in the parent and send a single button down as props:
const buttons = [{*Button1*, *Button2*}]
render(
{buttons.map((button) => <Child button={button}>)}
)
Then you can access the button as you intend to in your Child-component.
Next time you ask a question please provide better information to what you are actually trying to do and what the problem (e.g. error message) is. Ask specific questions. This makes it easier to answer you.

Cannot render component images in component when using or mapping on state variable

I am having trouble understanding why I cannot get images to show up in my components. I have a boolean which indicates loading, and an array that gets filled async. When I finish, I set the boolean and the component re renders. Now, I want to create a card for each item in the array and put in in a card deck (this is from react-bootstrap if that wasn't obvious). I can do this with any given boolean and array, but not with the boolean and arrays created with React.useState... Why is that and how should I go about fixing this?
I encountered this problem quite a few hours ago, and have tracked down its source to this minimal working example that still reflects what I am trying to do, but I am unsure of what to do from here.
function TestCard() {
return (
<Card>
<Card.Img src="holder.js/200x200" />
</Card>
);
}
I am trying to render the following component:
function MainComponent() {
const [boolState, setBoolState] = React.useState(false);
const [arrayState, setArrayState] = React.useState([]);
React.useEffect(() => {
setTimeout(() => {
setBoolState(true);
setArrayState([1,2,3]);
}, 2000);
});
return (
<>
{/* This works */}
{
true &&
<CardDeck>
{
[1,2,3].map(_ => {
return (
<TestCard />
);
})
}
</CardDeck>
}
{/* This doesn't, why? */}
{
boolState &&
<CardDeck>
{
arrayState.map(_ => {
return (
<TestCard />
);
})
}
</CardDeck>
}
</>
);
}
Code sandbox

Categories