1

i have testdata.json file which contains json data, when i try to execute the code below i am getting an error as "A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object". what should i do now?

this is contestpreview.js file:

import React from 'react';

const ContestPreview = (contest) => {
  <div className = "contestPreview">
    <div>
      {contest.categoryName}
    </div>
    <div>
      {contest.contestName}
    </div>
  </div>
};
export default ContestPreview;

This my app.js file:

import React from 'react';
import Header from './Header';

import ContestPreview from './ContestPreview';
class App extends React.Component {     
  state= { test : 7};
  render(){
    return(<div>
      <div>
        <Header message = "Naming contests"/>
      </div>
      <div>    
        <ContestPreview {...this.props.contests}/>
      </div>
    </div>
  );
  }
};

export default App;

This is my index.js file:

import React from'react';
import ReactDom from 'react-dom';
import data from './testData';
console.log(data);
import App from './components/App';

ReactDom.render(
  <App contest = {data.contest}/>,
  document.getElementById('root')
 );
Chris
  • 57,622
  • 19
  • 111
  • 137
Abhilash Muttalli
  • 1,279
  • 6
  • 19
  • 23

1 Answers1

1

Your ContentPreview component doesn't return a React Component. It's a small error on your part, but you can fix this by either adding a return statement, or by replacing your curly-braces with parenthesis.

Like so:

const ContestPreview = (contest) => (
  <div className = "contestPreview">
    <div>
      {contest.categoryName}
    </div>
    <div>
      {contest.contestName}
    </div>
  </div>
);
export default ContestPreview;

or

const ContestPreview = (contest) => {
  return (
    <div className = "contestPreview">
      <div>
        {contest.categoryName}
      </div>
      <div>
        {contest.contestName}
      </div>
    </div>
  );
};
export default ContestPreview;

The latter allows you to add some application logic before the return, if you want (though discouraged).


Since you're using a stateless functional component, you may find my previous answer on the pros/cons of these interesting.

Good luck!

Community
  • 1
  • 1
Chris
  • 57,622
  • 19
  • 111
  • 137