0

I'm completely new React. I have done the tutorials but as always reading and doing are two seperate things. So starting a brand new app from scratch and have fallen at the first hurdle.

I have a component called AnswerBox and a component called GetAnswerButton but the html in GetAnswerButton is not being rendered so I assume its not being passed to the AnswerBox component. Only the AnswerBox html is being rendered. So question, could anyone please point out the error of my ways

 import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';


    class AnswerBox extends React.Component{

        render(){
            return(
                <GetAnswerButton />,
                <div className="answerBox"></div>
             )
        }
    }

    class GetAnswerButton extends React.Component {

        render() {
            return (
                <div>
                    <button>Click Me</button>
                </div>
            )
        }
    }

    ReactDOM.render(
        <AnswerBox />,
        document.getElementById('root')
    );

Heres a code pen of it working(or not working!!) Codepen

Barry Watts
  • 784
  • 2
  • 14
  • 43
  • 1
    Possible Duplicate of [how-to-return-multiple-lines-jsx-in-another-return-statement-in-react](https://stackoverflow.com/questions/23840997/how-to-return-multiple-lines-jsx-in-another-return-statement-in-react/48515131#48515131) – Shubham Khatri Apr 05 '18 at 10:48
  • You will find the answer in the link above. Either place `GetAnswerButton />` and the div inside an array, wrap them in a div, or use `React.Fragment`. Also, even though it's not correct, do use `
    ` (self-closing tag). It is considered better practise.
    – Chris Apr 05 '18 at 10:50
  • have a look at [this](https://stackoverflow.com/q/31284169/5476782) question also – Evhz Apr 05 '18 at 10:53

2 Answers2

1

try to update the code in the AnswerBox class as follows:

class AnswerBox extends React.Component{
  render(){
    return(
      <div>
        <GetAnswerButton />,
        <div className="answerBox"></div>
      </div>
    )
  }
}

You should have an error in console saying adjacent elements need to be wrapped into an enclosing one. Or similar.

Evhz
  • 8,852
  • 9
  • 51
  • 69
1
class AnswerBox extends React.Component {

  render() {
    return (
     <div>
       <GetAnswerButton />
       <div className="answerBox"></div>
     <div>
    )
  }
}

wrap your return inside AnswerBox with div or Fragment and it works. or put it inside [] because you return as array.

ivica.moke
  • 1,054
  • 2
  • 10
  • 19