Reputation: 133
I am trying to change the name of a component but my logic is all in the parent component and therefore cannot access this.props.name
.
Here is my start button
class StartButton extends React.Component {
render(props) {
return (
<button onClick={this.props.onClick}>{this.props.name}</button>
)
}
}
Within my Header
class I am using StartButton with a name='Start Button'
render() {
return (
<header>
<div className="headerContainer">
<div id="countdown">
<p>Countdown: <span id="countdownSpan"></span></p>
</div>
<div className="flex-item-header">
<StartButton
name='Start Button'. <------------------------------
onClick={() => this.handleClick()}
/>
</div>
<div>
<p>Word Count: <span id="noOfWords"></span></p>
</div>
</div>
</header>
)
}
}
This is the logic I want to use and need this in Header
class because it is activated by onClick
.
changeToRestartText = () => {
this.name = 'Restart Game'; <---------------------------
}
I know, this.name doesn't work, but I am not sure how to access name='Start Button'
and change its value. Any help would be appreciated!
Upvotes: 0
Views: 40
Reputation: 17618
Instead of thinking to change the prop like that (there is no such a way) you should try to use the state for that. Though there are other ways, I'm giving the naive example below. Keep a state, and according to it pass your prop.
class App extends React.Component {
state = {
restart: false
};
changeToRestartText = () => {
this.setState({ restart: true });
};
render() {
const { restart } = this.state;
return (
<div>
<StartButton
name={!restart ? "Start Button" : "Restart Game"}
onClick={() => this.handleClick()}
/>
<button onClick={this.changeToRestartText}>Change to restart</button>
</div>
);
}
}
class StartButton extends React.Component {
render(props) {
return <button onClick={this.props.onClick}>{this.props.name}</button>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />
Upvotes: 1