Got stuck building a quote machine in React

Hi everybody,

I am trying to create a quote machine with React but it does not work. I put all the child components in one, define a method in the parent’s state, passed the parent’s state as props to child components but it still doesn’t work. I cannot figure out where it is a problem with the method or with the render.

Do you have an idea what’s wrong here?

const quotes = [
  ["My life is my message.", "Mahatma Gandhi"], 
  ["I love those who can smile in trouble.", "Leonardo da Vinci"], 
];
const randomNumber = Math.floor(Math.random() * quotes.length);

//React:

class Text extends React.Component {
  constructor(props) {
    super(props);
  };
  
  render() {
    return (
      <div> 
        {this.props.text}
      </div>
    )
  };
};

class Author extends React.Component {
  constructor(props) {
    super(props);
  };
  
  render() {
    return (
      <div>
        {this.props.author}
      </div>
    )
  };
}

class NewQuote extends React.Component {
  constructor(props) {
    super(props);
  };
    
    render() {
      return (
        <button class="btn btn-primary">New Quote</button>
      );
    }
}

class QuoteBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "",
      author: ""
    };
    this.handleClick = this.handleClick.bind(this);
  };
  
  handleClick() {
    this.setState({
      text: quotes[randomNumber][0],
      author: quotes[randomNumber][1]
    })
  };
  
  render() {
    return (
      <div>
        <Text text={this.state.text} />
        <Author author={this.state.author} />
        <NewQuote onClick={this.handleClick} />
      </div>
    )
  };
};

ReactDOM.render(<Text />, document.getElementById("text"));
ReactDom.render(<Author />, document.getElementById("author"));
ReactDOM.render(<NewQuote />, document.getElementById("new-quote"));

You are defining QuoteBox as the parent component, handling all the logic and maintaining state, but you never mount QuoteBox anywhere.

When I mount it, how do I render the children in the right divs?

You make the parent component responsible for mounting the appropriate child components, just as you have done in your QuoteBox render method.

So you could get by with replacing the three ReactDOM calls with a single
ReactDOM.render(< QuoteBox />, document.getElementById(“text”));

I mean if I need the children in different divs (for example they are in different parts of the page), how can I render each of them in their own div element?