Barak David
Barak David

Reputation: 45

Implement a function component that accepts one props "name"

My code won't pass the test and I'm a bit lost on the syntax. This is what I'm trying to do:

My code in React:

export default class WithProps extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "value",
    };
  }

  render() {
    const { name } = name;
    if ({ name } == "" || undefined || null) {
      return <h1>Hi</h1>;
    }
    return <h1>Hi {this.props.name}</h1>;
  }
}

Upvotes: 0

Views: 83

Answers (3)

Aakash Rathee
Aakash Rathee

Reputation: 593

const WithProps = ({ name }) => {
  return <h1>Hi{name && ` ${name}`}</h1>;
};

export default WithProps;

Upvotes: 0

DecPK
DecPK

Reputation: 25408

Live Demo

Codesandbox Demo

App.js

import "./styles.css";
import WithProps from "./WithProps";

export default function App() {
  return <WithProps />;
}

WithProps.js

export default function WithProps({ name }) {
  return <h1>{`Hi ${name ?? ""}`}</h1>;
}

Upvotes: 0

user17364288
user17364288

Reputation:

Here is an example of a functional component with your code

    export const WithProps = ({ name )} => { 
      const [name, setName] = React.useState();
    
      return (
        <h1> 
        {name ? `Hi ${name}` : 'Hi'}
        </h1>
      );
    }
    <WithProps name="World" />

Here is a class component with your code

export default class WithProps extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "value",
    };
  }

  render() {
    const { name } = this.props;

    return (
        <h1> 
        {name ? `Hi ${name}` : 'Hi'}
        </h1>
      );
  }
}
    
    <WithProps name="World" />

Upvotes: 1

Related Questions