hao
hao

Reputation: 73

How to render component on click?

I have a function that waits for a click event from the user. I also have an <App/> component that I render once the DOM is loaded. When the click function fires, the function should cause another component <Table /> to render with the prop being a variable from the function. I want to be able to rerender this Table with a new prop each time the network is clicked. I was wondering if I can get some advice for how to structure my code to achieve this? My code looks like this so far (doesn't work, but it conveys what I'm trying to do)

let nodes = new DataSet([])
let edges = new DataSet([])
let options = {}
nodes.add({ id:0, label:'first' })
nodes.add({ id:1, label:'second' })
let data = { nodes: nodes, edges: edges }
const container = document.getElementById('network')
const network = new Network(container, data, options) //renders canvas

network.on('click', function(properties){
  const clicked = nodes.get(properties.nodes)
  return clicked;
}

class App extends Component {
render() {
  return(
    {<Table row={somehow grab 'clicked'} />}
  )
}

//in another doc
class Table extends Component{
  render(){
    return(
      <div> this.props.row </div>
    )
  }
}

EDIT: I moved the network.on function inside App and it works. However, the code was very ugly; I couldn't figure out another way to interact with the canvas rendered by VIS.js so I decided to switch to d3. Thanks for the answers :)

Upvotes: 0

Views: 459

Answers (1)

glinda93
glinda93

Reputation: 8459

You can use this working example as a template

const Table = () => {
   const [data, setData] = React.useState(['This is inital table data']);
   return (
      <React.Fragment>
      <button 
         onClick={() => {
           setData([...data, 'When button is clicked, table data state is updated with new row data']);
         }}
      >
          Add a row
      </button>
      <table>
         <tbody>
         {data.map((rowData, index) => (
             <tr key={index}>
                 <td>{rowData}</td>
             </tr>
         ))}
         </tbody>
      </table>
      </React.Fragment>
   );
};


class HelloWorld extends React.Component {
  render() {
    return (
      <Table />
    );
  }
}

ReactDOM.render(<HelloWorld />, document.getElementById('root'));
<html>

<body>
  <div id="root"></div>
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

</body>

</html>

Upvotes: 1

Related Questions