Reputation: 11
Following is code below and now I wanted to change the value of name within the same component? How do I achieve this??
render(){
return(
<div>
<p>{this.props.name}</p>
</div>
)
}
Upvotes: 0
Views: 23690
Reputation: 5623
You should not try to update props directly inside your component, But you can trigger an event in that component which will be catch by the parent which is passing that value as props to your component and than the parent component will update that value which will past to all of if child which receive that data as props.
import { Component } from 'react';
class Child extends Component {
render(){
return(
<div>
<h2>{this.props.name}</h2>
<button onClick={() => this.props.changeName("New name"); }>
Change Name
</button>
</div>
)
}
}
class Parent extends Component {
constructor() {
this.state = {
name: "Name"
}
}
handleChande (name) {
this.setState({name: name});
}
render() {
<div>
<Child changeName={this.handleChange} />
</div>
}
}
Upvotes: 2
Reputation: 9779
you can achieve that from different component like this.
App.js
import React from "react";
import ChildComponent from "./ChildComponent";
class App extends React.Component {
state = {
name: ""
};
handleChane = e => {
this.setState({ name: e.target.value });
};
render() {
const { name } = this.state;
return (
<div>
<ChildComponent name={name} handleChane={this.handleChane} />
</div>
);
}
}
ChildComponent.js
import React from "react";
function ChildComponent(props) {
return (
<div>
<input
type="text"
onChange={props.handleChane}
placeholder="enter your name"
/>
{props.name}
</div>
);
}
export default ChildComponent;
Upvotes: 0
Reputation: 1121
You can't change the value of props but you still have options to change values that you can use. You have two options: Either you change it from the parent component or you use state instead of props.
Option 1/Parent Change:
const ParentComponent = props => {
const [name, setName] = useState('')
return (
<div>
<button onClick={() => setName('test')}>Test</button>
<ChildComponent name={name} />
</div>
)
}
Where ChildComponent has your code to use this.props.name
.
Option 2/Use State:
const MyComponent = props => {
const [name, setName] = useState(props.name || '')
return (
{name}
)
}
Note: This is untested code for displaying ideas not to be copy-pasted.
Upvotes: 1
Reputation: 7682
props should not be changed in react, they are readonly
. update them in the parent component and then pass them down as the new value. the component receiving them should just be displaying them and the logic handling should occur at a higher level
Upvotes: 5