Answer the question
In order to leave comments, you need to log in
How to change the data of one component from another React?
There are 2 components, I want to change the fragment from h1 on click . I don’t know if I’m doing it right, I probably need it through setState . Not sure if I understood correctly how to use it.
import React from 'react';
import '../index.css'
import Cover from './Cover'
class Main extends React.Component {
constructor(props) {
super(props)
state = {
isClicked: false
}
this.changeName = changeName.bind(this);
}
render() {
return (
<div className="main">
<input className="input" placeholder="Username" />
<button onClick={this.changeName} className="submit-button">Submit</button>
</div>
)
}
changeName = () => {
this.setState({
isClicked: true
})
Cover.username = document.getElementById('input').nodeValue
}
}
export default Main
import React from 'react';
import '../index.css'
class Cover extends React.Component {
constructor(props) {
super(props)
this.username = 'username';
}
render() {
return (
<div className="cover">
<img className="logo" src="./assets/logo.svg" />
<h1 className="header">Welcome on board, {{username}}!</h1>
</div>
)
}
}
export default Cover
Answer the question
In order to leave comments, you need to log in
If convenient, you can change the data through the parent.
But it is more correct for your task to use redux , since the username may be needed in different parts of the application, and most likely it will come from the server.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question