I am creating a list.but my condition if i want to show those element which start from hello else all other element ignore.
can you please tell me how to know what is anchor text value ?
here is my code
<Tabs>
{data.map((i, idx) => (
<li key={idx}>
<a>{i}</a>
</li>
))}
</Tabs>
my Tabs.js
import React from "react";
export default function Tabs({ children }) {
const names = () => {
const namesData = [];
React.Children.forEach(children, (child) => {
console.log(child);
// if (child?.textcontent?.indexOf("hello")) {
// namesData.push(child);
// }
namesData.push(child);
});
return {
namesData
};
};
const { namesData = [] } = names();
return <ul>{namesData.map((i) => i)}</ul>;
}
NOTE : there is one solution to filter data initially while doing iteration using map.but I don't want to use this that solution
can we add here condition if child anchor tag has hello text then only I push in array
React.Children.forEach(children, (child) => {
console.log(child);
// if (child?.textcontent?.indexOf("hello")) {
// namesData.push(child);
// }
namesData.push(child);
});
whole code https://codesandbox.io/s/compassionate-goldberg-ey2lc?file=/src/tabs.js:0-460
Since children are react elements, they have props, which you can access. The props might contains children as well, and so on. Specifically for your use case, this would work (sandbox):
React.Children.forEach(children, (child) => {
const content = child.props?.children.props?.children;
if(typeof content === 'string' && content.startsWith('hello')) {
namesData.push(child);
}
});
However, I wouldn't go that way. This seems to be brittle, and dependent on the way React decides to model children. A better option would be to filter the original array to include only the data for the items, you wish to render (sandbox):
<Tabs>
{data
.filter(txt => txt.startsWith('hello'))
.map((i, idx) => (
<li key={idx}>
<a>{i}</a>
</li>
))}
</Tabs>
Just like that
import React from "react";
export default function Tabs({ children }) {
const names = () => {
const namesData = [];
React.Children.forEach(children, (child) => {
if(child?.props?.children?.props?.children.startsWith('hello')) namesData.push(child);
});
return {
namesData
};
};
const { namesData = [] } = names();
return <ul>{namesData.map((i) => i)}</ul>;
}