es6 react getting props in child component - reactjs

I've been migrating one of my apps to ES6 on node/react and I have a question about how props are passed down to children. I read a bunch of posts and some address this while others don't. Basically, what I've seen so far is this:
export default class SomeComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
{this.props.text} <<< Props used here
</div>
);
}
}
but I've been able to get my component to work with the following:
export default class SomeComponent extends React.Component {
constructor() {
super(); <<< notice no props in parentheses
}
render() {
return (
<div>
{this.props.text} <<< Props used here
</div>
);
}
}
is there a reason why I should pass the props in the parentheses for my constructor and the super call? or can I leave my code the way it is

You don't need to pass props to super unless you want to use this.props in constructor.
https://stackoverflow.com/a/34995257/3238350

You have to pass the props because you are extending from React.Component, otherwise you won't be allowed to access to this.props in the constructor.
It's some kind of composition pattern.

Related

React and react native: Unexpected token. A constructor, method, accessor, or property was expected.ts(1068)

I'm studying react-native. I have a problem I cannot solve it. State in react class component gives me error: unexpected token. But useState in functional component works fine. Sorry for my language. I'm from Mongolia.
Here is my class and functional component:
react-native-class-component
react-native-functional-component
How can I solve it?
Here in your class component you need to declare your state inside constructor like this
export default class Home extends Component{
constructor(props){
this.state = {}
}
render(){
return(
<View>
<Text></Text>
</View>
)
}
}
The way you have declared the state in your class component is wrong. It should be within your constructor.
export default class Home extends Component{
constructor(props){
this.state = {}
}
render(){
return(
…
)
}
}

What is the diffrence between the following ways of initalizing the state [duplicate]

I'm working in a new codebase. Normally, I would set up state like this in a React component:
class App extends React.Component {
constructor() {
super();
this.state={
foo: 'bar'
}
}
....
In this new codebase, I'm seeing a lot of this:
class App extends React.Component {
state={
foo: 'bar'
}
....
Is there an advantage to doing it this way? They seem to only do it when state doesn't need to be altered. I always thought of state as being something React handled. Is this an ok thing to do?
The end result of both approaches is the same. Both approaches are just setting the initial state of the component. It's worth noting that class properties are a stage 3 proposal, so all development environments may not be able to use them.
I personally like to use the class field variant if nothing else is done in the constructor, as it is less code to write, and you have no super call to worry about.
Example
class Component1 extends React.Component {
state = { value: this.props.initialValue };
render() {
return <div> {this.state.value} </div>
}
}
class Component2 extends React.Component {
constructor(props) {
super(props);
this.state = { value: props.initialValue };
}
render() {
return <div> {this.state.value} </div>
}
}
function App() {
return (
<div>
<Component1 initialValue={1} />
<Component2 initialValue={2} />
</div>
);
}
Actually both of them bind to this pointer. the this that made in constructor of class.
Totally you can access to local state by this.state but in first style you can pass props to constructor by super and then use it in state declaration, just like below:
class App extends React.Component {
constructor(props) {
super(props);
this.state={
foo: 'bar',
jaz: props.someParentState,
}
}
....
Awesome, you can access to props in constructor, isn't pretty? I definitely use this style for local state declaration.
Hope this helps you.

Props are empty on passing them to child class based components while filled when using functional component

It seems that props are not being passed to child component when my child component is a class based component. This is my parent component:
class ScreeningsList extends React.Component{
state = {screenings: [] };
componentDidMount = async () => {
const response = await apis.getAllScreenings();
this.setState({screenings: response.data});
}
render(){
return (
<div>
<ScrTest screeningsList = {this.state.screenings}/>
</div>
)
}
}
And here is my child component:
class ScrTest extends React.Component{
render(){
return (
<div className="screeningsContainer">
<h2>Title: {this.props.screeningsList._id}</h2>
</div>
)
}
}
Here I tried just to display id of the screening. The value in props did not exist. There were no props at all.
However when I use functional component and use the arrow function:
const ScreeningsToRender = props => {
...
}
I can access props by using props.screeningsList and use every value that is inside that prop. Rendering the component is succesfull and I can see the list of all the screenings. What should I do to recieve props properly in my child component?
You need a constructor in the child component:
class ScrTest extends React.Component{
constructor(props){
super(props);
}
render(){
return (
<div className="screeningsContainer">
<h2>Title: {this.props.screeningsList._id}</h2>
</div>
)
}
}
"When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor".
Source: https://reactjs.org/docs/react-component.html#constructor

Pass event through nested components bottom to top

While this question has been asked before I did not find an answer. I have components nested to the level of great grandchild and I don't know how to get the data from the bottom to the top.
<Parent/>
<Child/>
<GrandChild/>
<GreatGrandChild/>
See an example: fiddle
The great grandchild is a form and I want the input data to get to the parent at the top. I had it working when it was just nested one level deep, but now that it is deeply nested it does not work. I'm not sure how to even pass the event up two levels.
I've heard using redux is possible but I wonder if there is a way to avoid it. Or, how do I avoid the nesting? Even through they are all actually separate components should I just move them into one big component? This might work but seems like bad practice?
Very simplified, you could just pass the function through all the components:
class GreatGrandChild extends React.Component {
render() {
return (
<div>
<input onChange={this.props.onChange}/>
<h2>I'm the GreatGrandChild</h2>
</div>
)
}
}
class GrandChild extends React.Component {
render() {
return (
<div>
<h2>I'm the GrandChild</h2>
<GreatGrandChild onChange={this.props.onChange}/>
</div>
)
}
}
class Child extends React.Component {
render() {
return (
<div>
<GrandChild onChange={this.props.onChange}/>
<h2>I'm the child</h2>
</div>
)
}
}
class Top extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
handleChildchange = (e) => {
console.log('child event on parent')
console.log(e.target.value);
}
render() {
return (
<div>
<Child onChange={this.handleChildchange}/>
<h2>I'm the parent</h2>
</div>
)
}
}
ReactDOM.render(<Top />, document.querySelector("#app"))
Redux is overkill for simple passing of props. You can pass props down through each child but it's easier to use the Context API like so:
Parent Component:
const MyContext = React.createContext('default');
export MyContext;
class Parent extends React.Component {
myFunction() {
//Do something here
}
render() {
return (
<MyContext.Provider value={this.myFunction}>
<ChildComponent />
</MyContext.Provider>
);
}
}
export default Parent;
Child Component:
import { MyContext } from './Parent';
class ChildComponent extends React.Component {
render() {
const { myFunction } = this.context;
return (
<div onClick={myFunction}>Click Me!</div>
);
}
}
ChildComponent.contextType = MyContext;
You can use the context as deep as you'd like, as long as you import it.
Simply pass a callback down from the parent via the props and make Sure it's passed all the way down to where you need it.
You also can pass props to your each child component in nesting and whenever values changed, you can call a parent function (nested) to get latest values in parent.

reactjs base class for all components

I want to have a base component that all my higher order components extends it. Something along the lines of
<BaseComponent>
<App1>
<... Other Components>
</App1>
</BaseComponent>
where BaseComponent contains things such as
class BaseComponent extends React.Component {
render() {
return (
<Wrapper>
{this.props.children}
<ModalContainer>
</ModalContainer>
<Wrapper>);
}
}
The ultimate goal is to be able to, in any of the Apps pass lets say "message = 'Error'" and a modal dialog will display saying "Error" without having to put the modal component in every single app.
Is this possible? or am I in the realm of unicorns. I read a little about higher order compositions but at first glance, it doesn't seem like that's what i'm looking for.
Component composition via higher-order components is a way to do something like subclassing but with composition instead of inheritance. For example:
function wrapInBaseComponent(Component) {
// Return a new component that renders `Component`
// with all the same props, but also renders some
// other stuff
return (props) => {
const { message, ...otherProps } = props;
return (
<Wrapper>
<Component {...otherProps} />
<ModalContainer message={message}>
</ModalContainer>
</Wrapper>
);
};
}
Then you'd do something like this:
class MyComponent extends React.Component {
// ...
}
const WrappedComponent = wrapInBaseComponent(MyComponent);
Or, if you have ES7 decorators enabled, you can use it as a decorator:
#wrapInBaseComponent
class MyComponent extends React.Component {
// ...
}
This is how things like react-redux and react-dnd work; you don't inherit from ReactReduxBaseComponent or anything like that, you compose your component in a higher-order component that renders it, but adds additional functionality.

Resources