user3622460
user3622460

Reputation: 1251

How can I return a React Component from a mapping?

Hello I have a list of slides I am displaying based on this.props.name. I have all the slides listed in a mapping array and I would like to render them out 1 replacing the other based on a button press from the container component. I am having trouble just rendering the component out.

The button on the container div properly basses the SlideTest component the correct name, such as Slide1, Slide2, Slide3, etc. I would like SlideTest to take this name and render the component. I can only return something like Slide1, which isn't the component which is what I ideally would like.

export const mapping = { Slide1, Slide2, Slide3, Slide4 }

Here is the component using the mapping

import React, { Component, PropTypes } from 'react'
import sass from '../scss/application.scss'
import { mapping } from './AllSlides'


class SlideContainer extends Component {
    constructor(props){
        super(props)
            this.state = {
                name: '',
            }
    }   

    render() {

        const curSlide = () => {
            console.log(mapping[this.props.name]);
            return mapping[this.props.name];
         }

        return(
            <div>
                <center>
                    {curSlide()}
                </center>
            </div>
        )
    }
}

SlideContainer.propTypes = {
    name: PropTypes.string
}

export default SlideContainer;

Here is the handleClick function for the button on the outside Container.

handleClick(e) {
        e.preventDefault();
        let tempCount = this.state.count + 1;
        let curSlide = `Slide${tempCount}`;

        this.setState({
            name: curSlide,
            count: tempCount
        });
    }

Upvotes: 0

Views: 151

Answers (1)

Chad
Chad

Reputation: 618

I would pass the rendering information to a Slide component. Or better yet pass the slide props into SlideContainer to render out the new slide. Check out ReactCSSTransitionGroup if you want a sliding animation.

render() {
    const Slide1 = {slide: 'slide1', src: 'url1'}
    const Slide2 = {slide: 'slide2', src: 'url2'}
    const Slide3 = {slide: 'slide3', src: 'url3'}
    const Slide4 = {slide: 'slide4', src: 'url4'}

    const mapping = { Slide1, Slide2, Slide3, Slide4 };
    const slide = mapping['Slide2']; //or this.props.name

    return(
        <div>
            <center>
                <Slide name={slide.slide} url={slide.url}/>
            </center>
        </div>
    )
}

Upvotes: 0

Related Questions