user10398929
user10398929

Reputation:

Passing props from one component to other component

I am trying to pass value "red" from index.js to box.js yet not working. Basically, I have a component that defines property of box and I want to pass background color "red" from index.js to Box.js component.

// Box.js
import React from "react";
const box = {
  // here i would like to get the vlue name assign it to background
  background: this.props.name,
  width: "250px",
  height: "250px"
  // more code that defines how the box looks like here
};

export default Box;

  /// index.js
import React, { Component } from "react";
import { render } from "react-dom";
import Box from "./Box";
  render() {
 

    return (
     // when calling Box, I would like to pass the value red to varivable name as shown below
    <Box name="red"></Box>
    )
   
}

What am I missing?

Upvotes: 0

Views: 279

Answers (2)

Sina Khelil
Sina Khelil

Reputation: 1991

You need to create a proper component:

// box.js
import React from "react";
const Box = (props) => {
  // here i would like to get the value name assign it to background
  const background = props.name;
  const width = "250px";
  const height = "250px";
  // more code that defines how the box looks like here
  return (
    // jsx code goes here
  );
};

export default Box;

in your second snippet, you are not using it properly

// index.js
import React from "react";
import Box from "./box"; // assuming that the file name is box.js and it is in the same folder

const BoxDisplay = (props) => {
    return (
       <Box name="red"/>
    );
};

export default BoxDisplay;

Or if you want an actual Component:

// index.js
import React, {Component} from "react";
import Box from "./box";

export default class BoxDisplay extends Component({
    constructor(props) {
        super(props)
        this.state = { //any initial state you want}
    }
    render() {
        return (<Box name="red"/>)
    }
});

Upvotes: 1

Mouleesh Guru
Mouleesh Guru

Reputation: 55

There is some confusion in the question, please help us understand your problem in detail.

  • Your default export name is "card " and you are trying to import "Box".
  • what do you mean by main source code?
  • Your index.js is not having a proper component syntax

please note that you cannot use "this.props" if you are not using a class based component or constructor rather use "props"

try changing the Box component as below:

const Box = (props) => {
    return <p style={{background: props.name}}> Content </p>
}

Upvotes: 0

Related Questions