kokserek
kokserek

Reputation: 589

How to pass the props dynamically?

I am trying to learn how to use react-polls (for further communication with backend, so, some fragments of my code are prepared for next steps). The problem is: I expect to see 123 in my browser (as in componentDidMount), but I don't.

When I pass the string '123' directly instead of const pollQuestion = props => (<div>{props.quest}</div>); it works.

//imports

import Poll from 'react-polls';


const pollQuestion = props => (<div>{props.quest}</div>);

const pollAnswers = [
  { option: 'Yes', votes: 8 },
  { option: 'No', votes: 2 }
]

class PollQuestion extends Component {
  state = {
    pollAnswers: [...pollAnswers]
  }

  handleVote = voteAnswer => {
    const { pollAnswers } = this.state
    const newPollAnswers = pollAnswers.map(answer => {
      if (answer.option === voteAnswer) answer.votes++
      return answer
    })
    this.setState({
      pollAnswers: newPollAnswers
    })
  }

  render () {
    const { pollAnswers } = this.state
    return (
      <div>
        <Poll question={pollQuestion} answers={pollAnswers} onVote={this.handleVote} />
        <p>It works</p>
      </div>
    );
  }
};

class QuestionList extends Component {
    state = {
        questions: []
    }

    componentDidMount(){
                this.setState({ questions: [{question_text:'123'}]});
    }

    render(){
        return (
            <div>{this.state.questions?
                <ul>
                    <PollQuestion quest={this.state.questions.slice(0, 1).map(question => <li>{question.question_text}</li>)} />
                </ul>:null}
            </div>
        )
    }
};


function AppV() {
  return (
    <div className="App">
      <QuestionList/>
    </div>
  );
}

export default AppV;

Upvotes: 1

Views: 103

Answers (2)

Dhananjai Pai
Dhananjai Pai

Reputation: 6005

The problem was you were not passing the value of this.props.quest to the pollQuestion element. Either do this

<Poll question={this.props.quest} answers={pollAnswers} onVote={this.handleVote} />

See code here : https://stackblitz.com/edit/react-nngrut

OR do this

Edit 
const pollQuestion = props => (<div>{props.quest}</div>); to
const MyPollQuestion  = props => (<div>{props.quest}</div>);

<Poll question={<MyPollQuestion quest={this.props.quest} />} answers={pollAnswers} onVote={this.handleVote} />

https://stackblitz.com/edit/react-sxf2kx?file=AppV.js

Also, All react components should start with a capital letter.

Upvotes: 2

Vaibhav Singh
Vaibhav Singh

Reputation: 942

The

React-Polls question attribute has Proptype of string

and you are

trying to pass a React Element

to it that is why it is not working.

Pass you question string directly.

Upvotes: -1

Related Questions