y2UcDgAL
y2UcDgAL

Reputation: 41

Why I can't pass simple props in React..From parent to child

I am a beginner of React. I'm practicing using React to pass props from parent to child.

but.I can't pass props. I just want to pass simple props from parent to child.

My code is here. https://codesandbox.io/s/props-test-3bgjy?file=/src/Child.js

My code is not showing the error. But my code doesn't display correctly.


import React, { Component } from "react";
import styled from "styled-components";
import Child from "./Child";

const Button = styled.button`
  font-size: 16px;
  padding: 16px;
`;

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0,
      msg: "state(msg)initial",
      flg: true
    };
    this.doAction = this.doAction.bind(this);
  }

  doAction() {
    this.setState((state) => ({
      counter: state.counter + 1,
      msg: state.counter,
      flg: !state.flg
    }));
  }

  render() {
    return (
      <div>
        <Child msg={this.state.message} flag={this.state.flag} />
        <Button onClick={this.doAction}>Click</Button>
      </div>
    );
  }
}

export default App;


import React, { Component } from "react";
import styled from "styled-components";

const Message = styled.p`
  font-size: 24pt;
  color: #900;
  margin: 20px 0px;
  padding: 5px;
  border-bottom: 2px solid #900;

  &[data-primary="true"] {
    font-size: 24pt;
    color: white;
    background-color: #900;
    margin: 20px 0px;
    padding: 5px;
    border-bottom: 2px solid #900;
  }
`;

class Child extends Component {
  render() {
    return (
      <div>
        <Message data-primary={this.props.flag}>
          count: {this.props.msg}
        </Message>
      </div>
    );
  }
}

export default Child;

Upvotes: 0

Views: 562

Answers (2)

Ethan Keshishian
Ethan Keshishian

Reputation: 83

It looks like you have a typo; change this line:

<Child msg={this.state.message} flag={this.state.flag} />

to

<Child msg={this.state.msg} flag={this.state.flg} />

Upvotes: 0

Alexander Kiselev
Alexander Kiselev

Reputation: 221

You are have mistake in line <Child msg={this.state.message} flag={this.state.flag} />

Need use state param msg

<Child msg={this.state.msg} flag={this.state.flag} />

https://codesandbox.io/s/props-test-forked-gw69r?file=/src/Parent.js

Upvotes: 1

Related Questions