Phillip R Phillip R - 1 month ago 17
React JSX Question

React with Semantic UI, Dynamically Add Props

Semantic-UI has this React component, Segment that I am using.

In my application, I am using onMouseOver with Segment, like so:

render() {
return (
<Segment onMouseOver={this.handleHover} />
);
}


What I want handleHover() to do is to dynamically add semantic UI props to Segment on the mouse over event. I tried doing this with react clone element, and adding a new color prop according to the Semantic UI docs

React docs state:


Clone and return a new React element using element as the starting
point. The resulting element will have the original element's props
with the new props merged in shallowly.


handleHover() {
React.cloneElement(Segment, {
color: "teal" //NEWLY ADDED
});

//THIS EXECUTES SO EVENT IS TRIGGERING.
console.log("I'm in here");
}


So even after cloning the React Component, it still doesn't show the new color attribute when I hover over the Segment.

Question: Is this the right approach to dynamically adding props? If so then why isn't the newly added color being shown. If not then how should I change my code?

Answer Source

You can add whatever prop value you want to the state of your current component, and change that value onMouseOver:

constructor(props) {
  super(props);

  this.state = {
    propValue: undefined
  }
  this.handleHover = this.handleHover.bind(this);
}

handleHover(event) {
  this.setState({propValue: 'hover'});
}

render() {
  return (
    <Segment onMouseOver={this.handleHover} propName={this.state.propValue} />
  );
}

The value of this.state.propValue will change from undefined to hover, and the Segment component will get that new prop when the onMouseOver callback get called.

You can change propName to color and this.state.propValue to 'teal', based on your example.