Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change button text dynamically in material-ui

If I try to change label button I got an error because label is a read only property. How could I change button text dinamically?

export default class Tagger extends Component {
  static propTypes = {
    name: PropTypes.string
  }

  constructor(props) {
    super(props)
    this.state = {
      disabled: true
    }
    this.enableEdit = this.enableEdit.bind(this)
  }

  componentDidMount() {
    this.editButton = React.findDOMNode(this.refs.editButton)
  }
  enableEdit() {
    this.setState({disabled: !this.state.disabled})
    this.refs.editButton.props.label = 'Save'
  }

  render() {
    return (
      <div>
        <RaisedButton onClick={this.enableEdit} label='Modify' primary={true} ref='editButton' />
      </div>
    )
  }
}
like image 558
user2670996 Avatar asked Sep 13 '25 16:09

user2670996


1 Answers

Props are read-only , you can't mutate/edit them

You can simply change the props instead of mutating them. Set the value of the prop to state and simply pass it.

export default class Tagger extends Component {
  static propTypes = {
    name: PropTypes.string,
  }

  constructor(props) {
    super(props)
    this.state = {
      disabled: true,
      label = "Modify" // initial state
    }
    this.enableEdit = this.enableEdit.bind(this)
  }

  componentDidMount() {
    this.editButton = React.findDOMNode(this.refs.editButton)
  }
  enableEdit() {
    this.setState({
    disabled: !this.state.disabled,
    label:"Save" // update it here
    })
  }

  render() {
    // take value from state and pass it, no need for ref
    return (
      <div>
        <RaisedButton onClick={this.enableEdit} label={this.state.label} primary={true} />
      </div>
    )
  }
}
like image 58
StateLess Avatar answered Sep 16 '25 07:09

StateLess