Search code examples
javascriptreactjscorscodesandbox

A cross-origin error was thrown problem with Codesandbox.io


I have "A cross-origin error was thrown" Error in Codesanbox.io when i tried to execute this code. please what can i do to go over ? I'm using Create-react-app with codesanbox.io

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";

class App extends React.Component {
  state = {
    customer: [
      { id: 1, name: "Leon" },
      { id: 1, name: "Lea" },
      { id: 1, name: "Vanelle" }
    ]
  };
  render() {
    const title = "Customer list";
    const elements = this.state.customer.map();
    return (
      <div className="App">
        <h1>{title}</h1>
        <ul>
          <li>
            Philippe <button>X</button>
          </li>
        </ul>
        <form>
          <input type="text" placeholder="Add a customer" />
          <button>Confirm</button>
        </form>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Solution

  • Your render function should map through each of the customer found in the state. Just calling this.state.customer.map() throws an error which it seems is not handled properly by codesandbox.

    Try this for your render:

    render() {
        const title = "Customer list";
        return (
          <div className="App">
            <h1>{title}</h1>
    
            <ul>
            {
              this.state.customer.map(c => (
                <li key={c.id}>
                 {c.name} <button>X</button>
                </li>
              ))
            }
            </ul>
            <form>
              <input type="text" placeholder="Add a customer" />
              <button>Confirm</button>
            </form>
          </div>
        );
      }