Search code examples
reactjsarrayscomponentsreact-propsreact-class-based-component

How can I call an array from one component to show in another component using Class Component in React-js?


I have a question that I believe that is simple, buuut I couldn't solve it and I didn't find something similar on the internet.

I have a React Component that have an array like state and I'm trying to take this array and put in another array into a select-option.

This is the Component with the array:

import React,{Component} from "react";


class CarList extends Component{
  constructor(props){
  super(props);
  this.state = {
    carList: ['Jeep', 'Kwid','HB20','Ônix', 'Prisma', 'Gol quadrado']
  }
  }


render(){
    return(
      <div>
        <select>
            {this.state.carList.map( (item,ii)=>{
                return(
                    <option key={ii}>{item}</option>
                )
            } )}
        </select>
      </div>
    );
  }
}


export default CarList;

And this is the Component that is render on React-dom:


import React from "react";
import { Component } from "react";
import CarList from "./components/Tabela";


class App extends Component{
constructor(props){
  super(props);
  this.state={
    
  }
}



render(){
  return(
    <div>
      <p>I got it! Here is the car list:</p>
      <select>
        {this.state.carList.map(  (item,x)=>{
          return(
            <option key={x}>{item}</option>
          )
        })}
      </select>
    
    </div>
  )
}
}

export default App;```

Hey!

I tried to call with a map();
I tried to import the component;
I tried to call the array just before import the component;

Solution

  • Not sure if I understand you correctly. Here is an option:

    From checking your App component code, the select component would give the same result as this:

      render() {
        return (
          <div>
            <p>I got it! Here is the car list:</p>
            <CarList />
          </div>
        );
      }