-1

I have a component which accepts an array as a prop

<Component runners={['1','2']}/>

Within this functional component, I want to render an element for each value in he array. My logic is:

const { runners } = props

if(runners.includes('1')) {
  return(<ElementOne/>)
}

if(runners.includes('2')) {
  return(<ElementTwo/>)
}

etc...

the includes method throws an error runners.includes is not a function. Same for indexOf. So I check typeOf runners which returns object. Then I output JSON.stringify(runners). And it returns "[1,2]".

I try to re-do the above conditionals with hasOwnProperty and in methods, and they all return false.

Any ideas what might work here?

  • 1
    I would avoid using the name `prop` as one of your component props. – johnborges Oct 10 '19 at 16:27
  • 1
    @johnborges prop was just an example, sorry. I just edited the code to reflect the real key. – Dan Kurfirst Oct 10 '19 at 16:30
  • Why are you destructing props? Is props the name of the property in the functional component. With what I can see, your props should be called runners and you do not need to destructure it, – Yuvi Oct 10 '19 at 16:39
  • This is not an answer but just an observation: you're passing array of strings, but then try to find a number. Have you checked https://stackoverflow.com/questions/43948828/how-to-pass-an-array-of-items-in-react-js ? – ahwayakchih Oct 10 '19 at 16:41
  • @ahwayakchih that was a typo on my part....I am in fact checking for string – Dan Kurfirst Oct 10 '19 at 16:49
  • Can you share bit more on the problem? Which browser etc... Because your code looks totally valid and works: https://codesandbox.io/s/angry-rgb-5gips?fontsize=14 – Andrey Oct 11 '19 at 08:55

2 Answers2

0

The problem is that prop is kind of a special word in react

Unless I get the exact code I cannot be sure, but assuming since it is a functional component that probably has prop as the argument, the solution is

prop.prop.includes(2)

the outer prop is the function argument, the inner prop is the actual key you passed to the Component

Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25
  • Thanks...it's not actually called prop I'm just using this as an example. The actuall me of the prop is ```runners```. And I have ``` const { runners } = props ``` above those conditions...so I dont think thats it. JSON.stringify outputs the correct value, but array/obj methods don't work. – Dan Kurfirst Oct 10 '19 at 16:28
0

enter image description here

Also add ReactDOM.render(, document.getElementById('root')); in your index.js from where the react components are basically rendered.

runners -> goes as the props value to the functional component named Prctc(here) and you can use the values of props by using {props.runners} ,since it is array I have iterated it and check the condition provided.Now you can return anything in the enclosing tag.

Ayushi Keshri
  • 680
  • 7
  • 18