Home > Mobile >  Implement a function component that accepts one props "name"
Implement a function component that accepts one props "name"

Time:11-15

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

  • Implement a simple function component that accepts one props "name"
  • and renders an h1 element with the text "Hi {name}" where {name} is
  • the value in the prop "name"
  • if name is empty (empty string, undefined or null), render "Hi "

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>;
  }
}

CodePudding user response:

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" />

CodePudding user response:

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>;
}

CodePudding user response:

const WithProps = ({ name }) => {
  return {name ? `Hi ${name}` : name};
};

export default WithProps;
  • Related