0

My component is a Filter, that receives as a prop some filters, which should be rendered. However props are not rendered:

<Filter key={i}/>

Code is here: https://www.webpackbin.com/bins/-KjI4MiSjlV69O_zaOCD

Filter component:

import React, { PropTypes } from 'react'
import Filter1 from './Filter1'
import Filter2 from './Filter2'


const Filters = ({ filters }) => (
  <div>
    { filters.reverse().map((Filter, i) =>
       // React.createElement(Filter, { key: i}) does not work
       // <p>{Filter}</p> // h
       <Filter key={i}/>

    )}
    <p> This should be seen twice!</p>
    <Filter1/>
    <Filter2/>
  </div>
)
Filters.propTypes = {
  filters: PropTypes.arrayOf(PropTypes.string).isRequired
}

export default Filters

One of the filters:

import React from 'react'

function Filter1 () {
  return (
    <h1>This is filter1</h1> 
  )
}

export default Filter1
4
  • Is there a question here? Commented May 4, 2017 at 11:55
  • 1
    Can't render the elements dynamically, edited my question. Commented May 4, 2017 at 12:09
  • Do you have to use strings? Commented May 4, 2017 at 12:28
  • Yes, I get values from redux, so they should be serializable Commented May 4, 2017 at 12:30

1 Answer 1

2

Change Filters.js like so:

import React, { PropTypes } from 'react'
import Filter1 from './Filter1'
import Filter2 from './Filter2'

const filters = {
  Filter1: Filter1,
  Filter2: Filter2
}
const Filters = (props) => (
  <div>
    { props.filters.reverse().map((filter, i) => {
        const Filter = filters[filter];
        return <Filter key={i}/>
      })
    }
    <p> This should be seen twice!</p>
    <Filter1/>
    <Filter2/>
  </div>
)
Filters.propTypes = {
  filters: PropTypes.arrayOf(PropTypes.string).isRequired
}

export default Filters

The key change is using an object, filters, that contains keys that match up with the strings you pass in. The values are the components you want to render.

Here is the edited webpackbin

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.