Home > Blockchain >  How to pass prop from one component to another?
How to pass prop from one component to another?

Time:05-03

I need to pass prop called name from one React component to another, but something goes wrong. Could you tell me how to do it right?

Thanks in advance

import React from 'react';

export class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello World and {this.props.name}</h1>
    )
  }
}
import React from 'react';
import ReactDOM from 'react-dom';
import Greeting from './Greeting';

function App() {
  return (
    <div>
      <Greeting name='Alex' />;
      <h2> Welcome, {Greetings.props.name} </h2>
    </div>
  );
}

export default App;

CodePudding user response:

two things:

  1. looks like you are mixing class and functional components, i recommend going for functional as its more common now. in that case the Greeting will look like this:
export function Greeting(props) {
  return (
    <h1>Hello World and {props.name}</h1>
  )
}
  1. you are passing the prop the the component, but you cant access it from its parent. you can create another variable for that:
const greetingName = "Alex";

function App() {
  return (
    <div>
      <Greeting name={greetingName} />;
      <h2> Welcome, {greetingName} </h2>
    </div>
  );
}

CodePudding user response:

In Greeting.js you have missed parameter

App.js

import React, { useState } from 'react';
import Greeting from './Greeting';

const App = () => {
  const [name, setName] = useState("")
  return (
    <div>
      <Greeting name="Alex" />
    </div>
  )
}

export default App

Greeting.js

import React from 'react'

const Greeting = (props) => {
    return (
        <div>
            <h1>Hello World and My name is {props.name}</h1>
        </div>
    )
}

export default Greeting
  • Related